Swift/iOS8 顺序 HTTP 请求

Swift/iOS8 Sequential HTTP requests

我前段时间写了一些代码,使用用户输入的凭据登录网站,然后导航到某个页面以解析那里的信息(使用 NSURLConnectionDelegate)。

func startConnection() {
    var url = NSURL(string:"https://www.website.com/psp/ps/?cmd=login&languageCd=ENG")
    var request = NSMutableURLRequest(URL: url!)
    request.HTTPMethod = "POST"

    let data = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)

    request.HTTPBody = data

    request.setValue("\(data!.length)", forHTTPHeaderField: "Content-Length")
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.setValue("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", forHTTPHeaderField: "Accept")

    connection1 = NSURLConnection(request: request, delegate: self, startImmediately: false)!

    connection1.start()
}

func connectionDidFinishLoading(connection: NSURLConnection) {

    if (connection == connection1) {
        let url = NSURL(string: "https://www.nexturl.com")
        var request = NSMutableURLRequest(URL: url!)
        connection2 = NSURLConnection(request: request, delegate: self, startImmediately: false)!
        connection2.start()

    }

    if (connection == connection2) {

        let url = NSURL(string: "https://www.nexturl.com")
        var request = NSMutableURLRequest(URL: url!)
        connection3 = NSURLConnection(request: request, delegate: self, startImmediately: false)!
        connection3.start()
    }

    if (connection == connection3) {
        let strData: NSString = NSString(data: responseData, encoding: NSUTF8StringEncoding)!
        parse(strData)


    }

}

总体思路是触发一个初始请求,然后从委托方法 connectionDidFinishLoading 发送其他请求。有没有 cleaner/better 方法来进行这种顺序调用?

所以我使用 Alamofire 框架(AFNetworking 的新版本)做到了:

    var loginRequest = NSMutableURLRequest(URL: NSURL(string:"login.com")!)
    loginRequest.HTTPMethod = "POST"

    loginRequest.HTTPBody = ("timezoneOffset=-600&userid1=\(username)&userid=\(username.capitalizedString)&pwd=\(pass)&x=31&y=12" as NSString).dataUsingEncoding(NSUTF8StringEncoding)

    let manager = Alamofire.Manager.sharedInstance

    // Chain requests
    manager.request(loginRequest)
        .responseString{ (request, response, string, error) in
            if response!.statusCode == 500 {
                return Error.InternalServerError
            }
            else {

            manager.request(.GET, "www.redirect.com")
                .responseString { (request, response, string, error) in
                    println(string)
            }
        }
    }