我前段时间写了一些代码,登录到用户输入凭据的网站,然后导航到某个页面以解析那里的信息(使用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
发送其他请求。是否有更清洁/更好的方式来进行这种顺序呼叫?
答案 0 :(得分:2)
所以我使用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)
}
}
}