我已经为发出GET请求编写了此类
class GETReq{
func HTTPsendRequest(request: NSMutableURLRequest, callback: (String, String?) -> Void) {
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in
dispatch_async(dispatch_get_main_queue()) {
if (error != nil) {
callback("", error.localizedDescription)
} else {
callback(NSString(data: data,encoding: NSUTF8StringEncoding)!, nil)
}
}
}
task.resume()
}
func HTTPGet(url: String, callback: (String, String?) -> Void) {
var request = NSMutableURLRequest(URL: NSURL(string: url)!)
HTTPsendRequest(request, callback) }
}
在另一个名为“ ManageData”的类中
class ManageData{
func makeTheRequest()->String{
var makeReq:GETReq=GETReq();
var ret:String="";
makeReq.HTTPGet("http://www.example.com/fileExample.php") { (data:String, error:String?) -> Void in
if(error==nil){ ret="error"; } else { ret="ok"; }
}
return ret;
}
}
问题是在ViewController类中
var result:String = manageData.makeTheRequest();
“ result”变量始终为空,因为makeTheRequest函数在完成get请求之前会返回“ ret”。
您应该makeTheRequest
采用与其他地方相同的完成关闭模式。因此,更改makeTheRequest
为不返回任何值,而是采用一个callback
参数,该参数是在请求完成时将调用的闭包:
func makeTheRequest(callback: (String, String?) -> Void) {
var makeReq:GETReq=GETReq();
var ret:String="";
makeReq.HTTPGet("http://www.example.com/fileExample.php", callback)
}
您大概会这样称呼它:
makeTheRequest() { string, error in
if error != nil {
println(error)
return
}
// if you got here, you can use `string`
println(string)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句