无法调用非函数类型'JSON'的值,如何从Swift中的块返回值

时间:2015-09-27 03:18:58

标签: ios json swift

我有一个功能:

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()
}

我所要做的就是在调用此函数时返回NSDictionary JSON序列化字典。但似乎我不能,因为我的json数据在dataTaskWithRequest块中。我尝试过使用回调,但它显示错误:

Cannot call value of non-function type 'JSON'

有人能指出我解决这个问题的方向吗?

我使用SwiftyJSON作为第三方库。

1 个答案:

答案 0 :(得分:2)

试试这个:

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()
}

然后将其称为:

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
        }
    }
}