我是swift的新手,我有以下代码
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选项在下载后返回数据。我在网上搜索代码但找不到任何代码。任何有关代码的帮助都非常感谢。
谢谢
答案 0 :(得分: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
或者它的类型,因此您必须进行一些更改。