我正在尝试做2个HTTP请求 在第一个请求中,我将获得将在第二个请求中使用的var。 我的问题是,当我使用下面的代码执行它时,它只运行第二个请求而不运行第一个请求。
let url = NSURL(string:"https://loginurl")
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
let request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 2.0)
request.HTTPMethod = "POST"
let contentType = " application/x-www-form-urlencoded"
NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)
var dataString = "user details"
var requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = requestBodyData
NSURLProtocol.setProperty(requestBodyData!.length, forKey: "Content-Length", inRequest: request)
var response: NSURLResponse?
let session = NSURLSession.sharedSession()
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
//code for getting the session id to be used in the second request
})
task.resume()
let url2 = NSURL(string:"http://url2?sessionid")
let request2 = NSMutableURLRequest(URL: url2!, cachePolicy: cachePolicy, timeoutInterval: 2.0)
request2.HTTPMethod = "GET"
dataString=""
requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request2.HTTPBody = requestBodyData
NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request2)
task = session.dataTaskWithRequest(request2, completionHandler: {data, response, error -> Void in
})
task.resume()
任何人都可以解释这段代码可能出现的问题
问题2:
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if let httpRes = response as? NSHTTPURLResponse {
let html = NSString(data:data!, encoding:NSUTF8StringEncoding)
if let match = html?.rangeOfString("(?<=sessionid=')[^\';]+", options: .RegularExpressionSearch) {
portalid = (html?.substringWithRange(match))!
}
}
当我在模拟器中运行它没有问题,但是当我在iPhone上调试它时崩溃显示此错误“由于未捕获的异常终止应用程序'NSRangeException',原因:' - [__ NSCFString substringWithRange:]:范围{9223372036854775807,0超出范围;字符串长度52427'“ 感谢
答案 0 :(得分:1)
以下是提出两个请求的代码示例:
//: Playground - noun: a place where people can play
import UIKit
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
let session = NSURLSession.sharedSession()
session.dataTaskWithURL(NSURL(string: "http://www.google.com")!, completionHandler: { (data :NSData?, response :NSURLResponse?, error :NSError?) -> Void in
let res = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(res!)
// make a new request here
let innerSession = NSURLSession.sharedSession()
innerSession.dataTaskWithURL(NSURL(string: "http://www.google.com")!, completionHandler: { (data :NSData?, response :NSURLResponse?, error :NSError?) -> Void in
let res = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(res!)
}).resume()
}).resume()