2017-07-02 22 views
0

請填寫完整的jsonData數組 ,我想在關閉後處理值。使用轉義關閉值

func getNewsAsDic(completionHandler: @escaping ([fullJsonData]) -> [fullJsonData]) { 

    let session = URLSession.shared 
    let dataTask = session.dataTask(with: requestNewsForToday()) { data, _, error in 
     if error == nil { 
      if let dic = try? JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary { 
       var dataArray = [fullJsonData]() 

       let jdata = dic?["articles"] as! [[String:Any]] 

       for item in jdata { 

        let data = fullJsonData(author: item["author"] as? String, 
              description: item["description"] as? String, 
              publishedAt: item["publishedAt"] as? String, 
              title: item["title"] as? String, 
              url: item["url"] as! String, 
              imageURL: item["urlToImage"] as? String) 

        print(item["author"] as! String) 
        print(item["description"] as! String) 
        print(item["title"] as! String) 
        print(item["urlToImage"] as! String) 
        print(item["url"] as! String) 
        print(item["urlToImage"] as! String) 
        print(item["publishedAt"] as! String) 

        dataArray.append(data) 
       } 
       completionHandler(dataArray) 
       print(jdata.count) 
      } 
     } else { 
      return 
     } 
    } 
    dataTask.resume() 
} 

所以問題是: 1)Xcode的錯誤,什麼Result of call is unused, but produces '[fullJsonData]' 2)然後我試圖使用它的項目是這樣的:

var dataArray = [fullJsonData]() 
     dataArray = NetworkManager.shared.getNewsAsDic(completionHandler: { dict in 
      return dict 
     }) 

有一個錯誤太:Cannot assign value of type '()' to type '[fullJsonData]'

那麼這是真正的接受和使用閉包的值?

func getNewsAsDic(completionHandler: @escaping ([fullJsonData]) -> [fullJsonData]) { 

到:

回答

0

您應該在完成處理程序的簽名更改

func getNewsAsDic(completionHandler: @escaping ([fullJsonData]) -> Void) { 

然後你的電話更改爲:

NetworkManager.shared.getNewsAsDic(completionHandler: { myArray in 
    // Do whatever you want with myArray here 
}) 

此外,你應該重新命名getNewsAsDic因爲你真的返回一個數組。

+0

但我想用關閉之外的myArr值做一些事情。像其他函數中的計數和實現 –

+0

對'session.dataTask'的調用是異步(或非阻塞),因爲即使從服務器獲取答覆可能需要20秒,代碼執行也不會停止。這就是爲什麼你有一個「完成」回調 - 這是你收到服務器響應時要執行的代碼的原因。 – paulvs

0

看來你必須使用

var dataArray: [fullJsonData] = [],而不是你的代碼。