任何帮助都会受到赞赏,我有一堆用来调用NSURLConnection Synchronous方法的类,但这已经不存在了。如何在继续之前等待响应的方式调用此代码块?
class func login(email:String,password:String)->Int{
var userId = 0
let postEndpoint:String = "https://www.testsite.com/user/login.php"
let url = NSURL(string: postEndpoint)!
let urlRequest = NSMutableURLRequest(URL: url, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 15.0)
urlRequest.HTTPMethod = "POST"
let body = "email=\(email)&password=\(password)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
urlRequest.HTTPBody = body
let task = NSURLSession.sharedSession().dataTaskWithRequest(urlRequest) {(data, response, error) in
if data != "" && error == nil{
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [String: AnyObject]
if let id = json["id"] as? Int {
print("found id:\(id)")
userId = id
}
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
userId = 2
}
}
else{
userId = 2
}
}
task.resume()
return userId
}
代码叫这个......
success = User.login(emailTextField.text!, password: passwordTextField.text!)
print("success last: \(success)")
问题是最后的成功:"在返回用户标识之前调用。 Aaarrrrgggghhhhh!
答案 0 :(得分:3)
class func login(email:String,password:String)->Int{
var userId = 0
let postEndpoint:String = "https://www.testsite.com/user/login.php"
let url = NSURL(string: postEndpoint)!
let urlRequest = NSMutableURLRequest(URL: url, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 15.0)
urlRequest.HTTPMethod = "POST"
let body = "email=\(email)&password=\(password)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
urlRequest.HTTPBody = body
let group = dispatch_group_create()
// Signal the beginning of the async task. The group won't
// finish until you call dispatch_group_leave()
dispatch_group_enter(group)
dispatch_group_async(group, dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)) {
let task = NSURLSession.sharedSession().dataTaskWithRequest(urlRequest) {(data, response, error) in
if data != "" && error == nil{
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [String: AnyObject]
if let id = json["id"] as? Int {
print("found id:\(id)")
userId = id
}
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
userId = 2
}
}
else {
userId = 2
}
// Signal the end of the async task
dispatch_group_leave(group)
}
task.resume()
}
// Wait 30 seconds for the group to be done
let timeout = dispatch_time(DISPATCH_TIME_NOW, 30_000_000_000)
dispatch_group_wait(group, timeout)
return userId
}
如果您不希望它超时,请将第二行替换为:
dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
假设您必须拨打3个网络服务。在完成所有3个申请之前,您的申请无法继续。您可以调用第一个服务,然后在完成块中调用第二个服务,依此类推。但是,您需要等待一段时间的罚款。
使用此模式,您可以同时呼叫所有3:
let group = dispatch_group_create()
dispatch_group_enter(group)
dispatch_group_enter(group)
dispatch_group_enter(group)
dispatch_group_async(group, dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)) {
let task1 = NSURLSession.sharedSession().dataTaskWithRequest(request1) {...
// handle response & error
dispatch_group_leave()
}
let task2 = NSURLSession.sharedSession().dataTaskWithRequest(request2) {...
// handle response & error
dispatch_group_leave()
}
let task3 = NSURLSession.sharedSession().dataTaskWithRequest(request3) {...
// handle response & error
dispatch_group_leave()
}
}
let timeout = dispatch_time(DISPATCH_TIME_NOW, 30_000_000_000)
dispatch_group_wait(group, timeout)
// proceed with your code...