2017-02-20 60 views
2

我試圖從api設置標籤上的文本,但似乎該函數甚至沒有被調用。請參閱下面的代碼片段。它有什麼問題嗎?Alamofire從JSON API下載

編輯:typealias DownloadComplete等=() - >()

var date: String = "" 

override func viewDidLoad() { 
    super.viewDidLoad() 

    timeLbl.text = date 

    // Do any additional setup after loading the view. 
} 

func downloadTimeData(completed: @escaping DownloadComplete) { 
    //Downloading forecast weather data for TableView 
    Alamofire.request(APIURL).responseJSON { response in 

     let result = response.result 

     if let dict = result.value as? Dictionary<String, AnyObject> { 
      if let currentDate = dict["fulldate"] as? String { 
       self.date = currentDate 
       print(self.date) 
       print("xxx") 
      } 
     } 
    completed() 
    } 
} 

回答

0

在你發佈你是不是叫downloadTimeData(completed:)任何地方的代碼。

你可以做,在viewDidAppear(_:)例如:

override func viewDidAppear(_ animated: Bool) { 
    super.viewDidAppear(animated) 

    downloadTimeData { 
     // The request has completed 
     timeLbl.text = date 
    } 
} 

請注意,您可以需要稍微改變了通話,這取決於DownloadComplete是如何定義的。

+0

我編輯它並定義了DownloadComplete –

+0

@HonzaValta我更新了我的答案。 – naglerrr

0

您正在設置timeLbl.text立即在頁面加載viewDidLoad,但你沒有告訴應用程序做任何事情。

你必須downloadTimeData移動到viewDidLoad中,並在完成後,設置「timeLbl.text =日期」

你必須設置某種文本佔位符或裝載機的同時,您的呼叫正在取得,因爲你不能保證它是即時的。

我們是否設置了一個標籤?或標籤的整個表格?

我改變了一些語法是「swiftier」

var date = "" 

override func viewDidLoad() { 
    super.viewDidLoad() 
    //call downloadTimeData here 
    downloadTimeData() { 
    //once we are in completion, this means internet call finished, so set label now 
    self.timeLbl.text = date 
    } 
} 

func downloadTimeData(completed: @escaping DownloadComplete) { 
//Downloading forecast weather data for TableView 
    Alamofire.request(APIURL).responseJSON { response in 
    guard let dict = response.result.value as? [String: AnyObject], let currentDate = dict["full date"] as? String else { 
     //handle error here if response fails to give you good data 
     completed() 
     return 
    } 
    self.date = currentDate 
    print(self.date) 
    print("xxx") 
    completed() 
    } 
} 
+0

我發佈DownloadComplete只是爲了確保一切都很清晰。 –

+0

好的,我調整了我的答案。 –

1

我想通了與簡單和容易的方式,通過alamofire documetation。

override func viewDidLoad() { 
    super.viewDidLoad() 

    Alamofire.request(APIURL).responseJSON { response in 
     print(response.result) // result of response serialization 
     let result = response.result 

     if let dict = result.value as? Dictionary<String, AnyObject> { 
      let currentDate = dict["fulldate"] as? String 
      self.timeLbl.text = currentDate 
      } 

    } 
}