[英]Cannot call value of non-function type 'JSON', How can I return value from block in Swift
I have a function: 我有一个功能:
func connectToWS(callback: (JSON)) -> Void {
let urlPath: String = "http://xxx.webservice.com"
let url: NSURL = NSURL(string: urlPath)!
let request: NSURLRequest = NSURLRequest(URL: url)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request){
(data, response, error) -> Void in
if error != nil {
} else {
let json:JSON = JSON(data: data!)
// RETURN?
}
}
task.resume()
}
All I'm trying to do is to return the NSDictionary JSON serialized dictionary when I call this function. 我要做的就是在调用此函数时返回NSDictionary JSON序列化字典。 But it seems like I can't because my json data is in the dataTaskWithRequest block. 但似乎我不能,因为我的json数据在dataTaskWithRequest块中。 I've tried using call back but it shows the error: 我尝试使用回叫,但显示错误:
Cannot call value of non-function type 'JSON'
Can anyone point me in the direction to solve this? 谁能指出我的解决方向?
I am using SwiftyJSON as a 3rd party library. 我正在使用SwiftyJSON作为第三方库。
Try this out: 试试看:
func connectToWS(callBack: ((data: NSData!, response: NSURLResponse!, error: NSError!) -> Void)?) {
let urlPath: String = "http://xxx.webservice.com"
let url: NSURL = NSURL(string: urlPath)!
let request: NSURLRequest = NSURLRequest(URL: url)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { data, response, error in
callBack?(data: data, response: response, error: error)
return
}
task.resume()
}
Then call this like: 然后像这样调用:
connectToWS() { data, response, error in
if error != nil {
if error.domain == NSURLErrorDomain && error.code == NSURLErrorTimedOut {
print("timed out") // note, `response` is likely `nil` if it timed out
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.