NSURLSession是IOS8开始出来的, 在ios开发中使用NSURLConnection后xcode会提示使用ios8开始使用Session,下面我来简单介绍下我使用的经验
1使用NSURLSession
objective-c
NSURLSession *session = [[NSURLSession alloc] init];
NSURLSession *session = NSURLSessionDataTask *task = [[NSURLSession alloc] init];
[session dataTaskWithRequest:request completionHandler:^(NSData*data,NSURLResponse *response,NSError *error){
NSLog(NSString(data: data, encoding: NSUTF8StringEncoding));
}];
[task resume];
swift
//声明
let session = NSURLSession.sharedSession()
let task:NSURLSessionDataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
print(NSString(data: data, encoding: NSUTF8StringEncoding))
}
task.resume()
下面我们自己来封装一个简单的Request方法
objective-c
博主犯懒了OC还没写
swift
func RequestURL() -> Void {
//访问网址
let request:NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: "http")!)
//设置超时时间
request.timeoutInterval = 60
//设置访问类型
request.HTTPMethod = "GET/POST"
//可以设置自己请求头参数
//request.addValue("value", forHTTPHeaderField: "key")
request.HTTPBody = "内容".dataUsingEncoding(NSUTF8StringEncoding)
let session = NSURLSession.sharedSession()
let task:NSURLSessionDataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
print(NSString(data: data!, encoding: NSUTF8StringEncoding))
}
task.resume()
}
//将闭包当做参数传递
func RequestURL(URL URL:String,method:String,callback:(data:NSData,response:NSURLResponse,error:NSError) -> Void) -> Void {
//访问网址
let request:NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URL)!)
//设置超时时间
request.timeoutInterval = 60
//设置访问类型
request.HTTPMethod = method //"GET/POST"
//可以设置自己请求头参数
//request.addValue("value", forHTTPHeaderField: "key")
request.HTTPBody = "内容".dataUsingEncoding(NSUTF8StringEncoding)
let session = NSURLSession.sharedSession()
let task:NSURLSessionDataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
callback(data:data!,response:response!,error:error!)
}
task.resume()
}