swift中的网络请求——NSURLSessionDataTask
来源:互联网 发布:德邦数据分析员累吗 编辑:程序博客网 时间:2024/06/16 22:20
学习地址:https://github.com/potato512/SYSwiftLearning
效果图
在swift中使用NSURLSessionDataTask进行网络编程。
// NSURLlet url:NSURL = NSURL(string:"http://rapapi.org/mockjsdata/22598/userloginGet")!// NSURLRequestlet request:NSURLRequest = NSURLRequest(URL:url)// NSURLSessionlet configuration:NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()let session:NSURLSession = NSURLSession(configuration: configuration) // NSURLSessionTasklet task:NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: { (data:NSData?,response:NSURLResponse?, error:NSError?) -> Void in if error == nil { do { let result:NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary print(result) dispatch_async(dispatch_get_main_queue(), { () -> Void in let message:String = result.objectForKey("msg") as! String let alert = UIAlertView(title: nil, message: message, delegate: nil, cancelButtonTitle: "OK") alert.show() }) } catch { } }})// 启动任务task.resume()
// NSURLlet url:NSURL = NSURL(string:"http://rapapi.org/mockjsdata/22598/userloginPostWithParams")!// NSURLRequestlet request:NSMutableURLRequest = NSMutableURLRequest(URL:url)request.HTTPMethod = "POST"// 参数// 方法1// let postString = "userName=devZhang&userPassword=devZhang"// request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)// 方法2let postDic :NSDictionary = ["userName":"devZhang","userPassword":"devZhang"]do { let data:NSData = try NSJSONSerialization.dataWithJSONObject(postDic, options: NSJSONWritingOptions.PrettyPrinted) request.HTTPBody = data } catch { } // NSURLSessionlet configuration:NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()let session:NSURLSession = NSURLSession(configuration: configuration) // NSURLSessionTasklet task:NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: { (data:NSData?,response:NSURLResponse?, error:NSError?) -> Void in if error == nil { do { let result:NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary print(result) dispatch_async(dispatch_get_main_queue(), { () -> Void in let message:String = result.objectForKey("msg") as! String let alert = UIAlertView(title: nil, message: message, delegate: nil, cancelButtonTitle: "OK") alert.show() }) } catch { } }})// 启动任务task.resume()
// 请求路径let url: NSURL = NSURL(string:"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON")!// 请求对象// 请求对象内部默认已经包含了请求头和请求方法(GET)let request: NSURLRequest = NSURLRequest(URL: url)// 会话对象,并设置代理/*第一个参数:会话对象的配置信息 defaultSessionConfiguration 表示默认配置第二个参数:谁成为代理,此处为控制器本身即self,协议 NSURLSessionDelegate第三个参数:队列,该队列决定代理方法在哪个线程中调用,可以传主队列|非主队列[NSOperationQueue mainQueue] 主队列: 代理方法在主线程中调用[[NSOperationQueue alloc]init] 非主队列: 代理方法在子线程中调用*/let session: NSURLSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: NSOperationQueue.mainQueue())// 根据会话对象创建一个Task(发送请求)let dataTask: NSURLSessionTask = session.dataTaskWithRequest(request)// 执行任务dataTask.resume()
// 接收到服务器响应的时候调用该方法func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) { // 响应头信息,即response print("didReceiveResponse--%@", response) // 注意:需要使用completionHandler回调告诉系统应该如何处理服务器返回的数据 // 默认是取消的 /* NSURLSessionResponseCancel = 0, 默认的处理方式,取消 NSURLSessionResponseAllow = 1, 接收服务器返回的数据 NSURLSessionResponseBecomeDownload = 2,变成一个下载请求 NSURLSessionResponseBecomeStream 变成一个流 */ completionHandler(NSURLSessionResponseDisposition.Allow)}
// 接收到服务器返回数据的时候会调用该方法,如果数据较大那么该方法可能会调用多次func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { print("didReceiveData--%@", data) // 拼接服务器返回的数据 if self.data == nil { self.data = NSMutableData() } self.data.appendData(data)}
// 当请求完成(成功|失败)的时候会调用该方法,如果请求失败,则error有值func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { if (error == nil) { //解析数据,JSON解析请参考http://www.cnblogs.com/wendingding/p/3815303.html var dict:NSDictionary? = nil do { dict = try NSJSONSerialization.JSONObjectWithData(self.data, options: NSJSONReadingOptions.init(rawValue: 0)) as? NSDictionary } catch { } print("%@", dict) }}
阅读全文
0 0
- swift中的网络请求——NSURLSessionDataTask
- iOS基础——网络请求之NSURLConnection、NSURLSessionDataTask
- swift中的网络请求——NSURLConnection
- 【iOS开发-网络】使用NSURLSessionDataTask发送get和post请求
- Swift 中的网络请求问题 OC(AFNetworking) && Swift(Alamofire)
- swift ——~——~第三方网络请求封装
- NSURLSessionDataTask发送Get/Post请求
- Swift之网络请求
- swift 网络请求 2
- Swift网络请求
- swift 网络请求
- Swift - 网络请求
- swift 网络请求
- swift网络请求封装
- Swift学习笔记(3)iOS 9 中的网络请求
- iOS之网络—— NSURLSessionDataTask文件离线断点下载、NSURLSession文件上传、AFN基本使用、Cocoapods安装
- swift开发网络篇—利用NSURLConnection GET请求和POST请求
- NSURLSessionDataTask
- C#自定义泛型类
- 关于网络传输中的编码
- 11.网站后台的查找
- Android逆向之动态调试总结
- The file is absent or does not have execute permission 启动tomcat异常
- swift中的网络请求——NSURLSessionDataTask
- 移动端点击时间和触摸滑动事件实现tab切换
- Angular+Boostrap-fileinput+formdata上传图片(前端代码)
- C/C++篇章一const
- NRL: network representation learning & NE: network embedding. 相关论文总结
- SpringMVC(二)—实现参数绑定
- svn服务端部署
- [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
- java.lang.Error: Unresolved compilation problems:解决方案