标签:
NSURLSession是iOS7出的API,在它之前常用的原生网络库是NSURLConnection,但是因为Connection的使用起来不是很方便 所以我们一直倾向于AFNetworking,AFNetworking的确非常强大 但是我们也不该遗忘NSURLSession 因为NSURLSession使用起来也很方便。
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() configuration.allowsCellularAccess = true configuration.discretionary = true configuration.timeoutIntervalForRequest = 30.0 configuration.timeoutIntervalForResource = 60.0 configuration.HTTPAdditionalHeaders = ["Accept" : "application/json"] configuration.HTTPMaximumConnectionsPerHost = 5
let session = NSURLSession.sharedSession() let session = NSURLSession(configuration: configuration) let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue())
let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue()) let url = NSURL(string: "some request path") let task = session.dataTaskWithURL(url!)
/* -------------------------------分割线------------------------------- */
let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue()) let url = NSURL(string: "some request path") let task = session.dataTaskWithURL(url!) { (data, response, error) in // 请求后操作 }
let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue()) let url = NSURL(string: "some request path") let request = NSURLRequest(URL: url!) let task = session.dataTaskWithRequest(request) /* -------------------------------分割线------------------------------- */
let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue()) let url = NSURL(string: "some request path") let request = NSURLRequest(URL: url!) let task = session.dataTaskWithRequest(request) { (data, response, error) in // 请求完成操作
let task = session.uploadTaskWithStreamedRequest(request) let task = session.uploadTaskWithRequest(request, fromData: someData) let task = session.uploadTaskWithRequest(request, fromFile: fileUrl) let task = session.uploadTaskWithRequest(request, fromData: someData) { (data, response, error) in // 上传完成操作 } let task = session.uploadTaskWithRequest(request, fromFile: fileUrl) { (data, response, error) in // 上传完成操作 }
let downloadTask = session.downloadTaskWithRequest(request) let downloadTask = session.downloadTaskWithRequest(request) { (url, response, error) in // 下载完成操作 }
let downloadTask = session.downloadTaskWithURL(url!) let downloadTask = session.downloadTaskWithURL(url!) { (url, response, error) in // 下载完成操作 }
let downloadTask = session.downloadTaskWithResumeData(resumeData) let downloadTask = session.downloadTaskWithResumeData(resumeData) { (url, response, error) in // 下载完成操作 }
标签:
原文地址:http://www.cnblogs.com/Alex-sk/p/5573837.html