gpt4 book ai didi

Swift/iOS8 顺序 HTTP 请求

转载 作者:行者123 更新时间:2023-11-28 13:18:14 24 4
gpt4 key购买 nike

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


}

}

总体思路是触发一个初始请求,然后从委托(delegate)方法 connectionDidFinishLoading 发送其他请求。有没有更干净/更好的方法来执行这种顺序调用?

最佳答案

所以我使用 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)
}
}
}

关于Swift/iOS8 顺序 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27932303/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com