2016-03-07 63 views
0

迅速uploadTaskWithRequest我非常新的快速的,我有以下代碼與didReceiveData

var data : AnyObject 


    let dict = jsonObject as NSDictionary 
    do 
    { 
     data = try NSJSONSerialization.dataWithJSONObject(dict, options:.PrettyPrinted) 

     let strData = NSString(data: data as! NSData, encoding: NSUTF8StringEncoding)! as String 

     data = strData.dataUsingEncoding(NSUTF8StringEncoding)! 


     let task = defaultSession.uploadTaskWithRequest(request, fromData: data as? NSData, 
      completionHandler: 
      {(data,response,error) in 

       guard let _:NSData = data, let _:NSURLResponse = response where error == nil 
       else { 
        return 
       } 

    }); 

    task.resume() 

}catch{ 

    return resultJson 
} 

的resultJson對象返回因爲有更多的日期一個空數組被下載,它需要再寄一次我想知道我的天氣可以使用didReceiveData選項在數據下載後返回數據。我在網上搜索代碼,但找不到任何代碼。任何幫助代碼非常感謝。

感謝

回答

1

你說得對,上載完成之前返回運行,因此,你不會得到想要的結果。我假設這個代碼是在一個函數中。您需要更改它以將閉包作爲參數。然後,當上傳完成後,您可以致電該關閉。喜歡的東西:

func doTheUpload(completion completionHandler: ((AnyObject?) -> Void)) { 
    var data : AnyObject 
    let dict = jsonObject as NSDictionary 
    do 
    { 
     data = try NSJSONSerialization.dataWithJSONObject(dict, options:.PrettyPrinted) 
     let strData = NSString(data: data as! NSData, encoding: NSUTF8StringEncoding)! as String 
     data = strData.dataUsingEncoding(NSUTF8StringEncoding)! 
     let task = defaultSession.uploadTaskWithRequest(request, fromData: data as? NSData, 
      completionHandler: 
      {(data,response,error) in 
       guard let _:NSData = data, let _:NSURLResponse = response where error == nil 
        completionhandler(resultJson) 
       else { 
        return 
       } 
     }); 
     task.resume() 
    }catch{ 
     // Do something for error 
    } 
} 

那麼你會稱其爲:

doTheUpload(completion: { 
    resultJson in 
    // use the result 
}) 

請注意,我不知道您取得resultJson或者是什麼類型的,所以你將不得不作出一些變化。

相關問題