如何在转移到下一行代码之前完成NSURLSession请求

时间:2015-11-03 02:00:35

标签: swift asynchronous nsurlsession synchronous

任何帮助都会受到赞赏,我有一堆用来调用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!

1 个答案:

答案 0 :(得分:3)

几年前我问了同样的问题。我没有得到那个答案。人们就像现在一样发表了同样的评论。我确实认为完成处理程序是一个更好的主意,但现在您正在使用Swift,您可以使用Grand Central Dispatch执行此操作:

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