参见英文答案 >
Storing values in completionHandlers – Swift1
我正在做HTTP请求并在我的func中得到响应.它返回响应的值.我这样做:
我正在做HTTP请求并在我的func中得到响应.它返回响应的值.我这样做:
NSURLConnection.sendAsynchronousRequest(request,queue: NSOperationQueue.mainQueue()) {(response,data,error) in println(NSString(data: data,encoding: NSUTF8StringEncoding)) stringResponse = NSString(data: data,encoding: NSUTF8StringEncoding) as! String if stringResponse == "0" { return false } else if stringResponse == "1" { return true } else { return false } }
解决方法
如果您希望获得响应后的值,请执行此操作.
func getResponse(completionHandler : ((isResponse : Bool) -> Void)) { NSURLConnection.sendAsynchronousRequest(request,encoding: NSUTF8StringEncoding) as! String if stringResponse == "0" { completionHandler(isResponse : false) } else if stringResponse == "1" { completionHandler(isResponse : true) } else { completionHandler(isResponse : false) } } }
现在你从哪里打来电话呢?
classObject.getResponse {(isResponse) -> Void in //Do your stuff with isResponse variable. }