博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Swift3.0:NSURLConnection的使用
阅读量:7071 次
发布时间:2019-06-28

本文共 8290 字,大约阅读时间需要 27 分钟。

一、介绍

 应用中也不必不可少的会使用网络通信,增强客户端和服务器的交互,可以使用NSURLConnection实现http通信。

 NSURLConnection提供了异步请求和同步请求两种请求方式。同步请求数据会造成主线程阻塞,通常不建议在请求大数据或者网络不畅时使用。

 不管是同步请求还是异步请求,建立通信的步骤都是一样的:

1、创建URL对象; 2、创建URLRequest对象; 3、创建NSURLConnection连接;

 NSURLConnection创建成功后,就创建了一个http连接。异步请求和同步请求的区别是:

1、创建了异步请求,用户还可以做其他的操作,请求会在另一个线程执行,通信结果及过程会在回调函数中执行; 2、创建了同步请求,用户需要在请求结束后才能做其他的操作,这也是通常造成主线程阻塞的原因。

 

二、示例

同步请求数据方法如下:

//同步请求数据方法如下:func httpSynchronousRequest(){            // 1、创建URL对象;    let url:URL! = URL(string:"http://api.iclient.ifeng.com/ClientNews?id=SYLB10,SYDT10");            // 2、创建Request对象;    let urlRequest:URLRequest = URLRequest(url:url);            // 3、发起NSURLConnection连接    NSURLConnection.sendAsynchronousRequest(urlRequest, queue: .main) { (response:URLResponse?, data:Data?, error:Error?) in                    if(error != nil){             print(error?.localizedDescription);        }else{             //let jsonStr = String(data: data!, encoding:String.Encoding.utf8);             //print(jsonStr)             do {                 let dic = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)                    print(dic)                } catch let error{                    print(error.localizedDescription);                }            }        }    }

异步请求数据方法如下:

//在控制器声明一个全局的变量,存储解析到的data数据 var jsonData:NSMutableData = NSMutableData()
//异步请求数据方法如下:func httpAsynchronousRequest(){     // 1、创建URL对象;     let url:URL! = URL(string:"http://api.iclient.ifeng.com/ClientNews?id=SYLB10,SYDT10");             // 2、创建Request对象;     let urlRequest:URLRequest = URLRequest(url:url);             // 3、发起NSURLConnection连接     let conn:NSURLConnection? = NSURLConnection(request:urlRequest,delegate:self)     conn?.schedule(in: .current, forMode: .defaultRunLoopMode)     conn?.start()}
// MARK - NSURLConnectionDataDelegateextension ViewController:NSURLConnectionDataDelegate{        func connection(_ connection: NSURLConnection, willSend request: URLRequest, redirectResponse response: URLResponse?) -> URLRequest? {                //发送请求        return request;    }        func connection(_ connection: NSURLConnection, didReceive response: URLResponse) {                //接收响应    }        func connection(_ connection: NSURLConnection, didReceive data: Data) {                //收到数据        self.jsonData.append(data);    }        func connection(_ connection: NSURLConnection, needNewBodyStream request: URLRequest) -> InputStream? {        //需要新的内容流        return request.httpBodyStream;    }        func connection(_ connection: NSURLConnection, didSendBodyData bytesWritten: Int, totalBytesWritten: Int, totalBytesExpectedToWrite: Int) {        //发送数据请求    }        func connection(_ connection: NSURLConnection, willCacheResponse cachedResponse: CachedURLResponse) -> CachedURLResponse? {        //缓存响应        return cachedResponse;    }        func connectionDidFinishLoading(_ connection: NSURLConnection) {        //请求结束        //let jsonStr = String(data: self.jsonData as Data, encoding:String.Encoding.utf8);        //print(jsonStr)        do {            let dic = try JSONSerialization.jsonObject(with: self.jsonData as Data, options: JSONSerialization.ReadingOptions.allowFragments)            print(dic)        } catch let error{            print(error.localizedDescription);        }    }}

 

三、解析结果:

(        {        currentPage = 1;        expiredTime = 180000;        item =         (                        {                comments = 134;                commentsUrl = "http://inews.ifeng.com/ispecial/913/index.shtml";                commentsall = 1818;                documentId = "imcp_crc_1063216227";                id = "http://api.iclient.ifeng.com/TopicApiForCmpp?topicid=913&json=y";                link =                 {                    type = topic2;                    url = "http://api.iclient.ifeng.com/TopicApiForCmpp?topicid=913&json=y";                    weburl = "http://api.iclient.ifeng.com/TopicApiForCmpp?topicid=913";                };                online = 0;                reftype = editor;                staticId = "client_special_913";                style =                 {                    attribute = "\U4e13\U9898";                    backreason =                     (                        "\U5185\U5bb9\U8d28\U91cf\U5dee",                        "\U65e7\U95fb\U3001\U91cd\U590d",                        "\U6807\U9898\U515a"                    );                    view = titleimg;                };                styleType = topic;                thumbnail = "http://d.ifengimg.com/w198_h141_q100/p3.ifengimg.com/cmpp/2017/04/02/77c9cacd305fbad2554272f27dfc42e2_size39_w168_h120.jpg";                title = "\U4e60\U8fd1\U5e73\U201c\U4e09\U4f1a\U201d\U5c3c\U5c3c\U65af\U6258";                type = topic2;            },                        {        ...........        ...........        ...........}

 

四、源码:

////  ViewController.swift//  NetWorkTest////  Created by 夏远全 on 2017/4/3.//  Copyright © 2017年 夏远全. All rights reserved.///* NSURLConnection的使用:  */import UIKitclass ViewController: UIViewController {    var jsonData:NSMutableData = NSMutableData()    override func viewDidLoad() {        super.viewDidLoad()        //httpSynchronousRequest()        //httpAsynchronousRequest()    }        //同步请求数据方法如下:    func httpSynchronousRequest(){                // 1、创建NSURL对象;        let url:URL! = URL(string:"http://api.iclient.ifeng.com/ClientNews?id=SYLB10,SYDT10");                // 2、创建Request对象;        let urlRequest:URLRequest = URLRequest(url:url);                // 3、发起NSURLConnection连接        NSURLConnection.sendAsynchronousRequest(urlRequest, queue: .main) { (response:URLResponse?, data:Data?, error:Error?) in                        if(error != nil){                print(error?.localizedDescription);            }else{                //let jsonStr = String(data: data!, encoding:String.Encoding.utf8);                //print(jsonStr)                do {                    let dic = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)                    print(dic)                } catch let error{                    print(error.localizedDescription);                }            }        }    }        //异步请求数据方法如下:    func httpAsynchronousRequest(){        // 1、创建NSURL对象;        let url:URL! = URL(string:"http://api.iclient.ifeng.com/ClientNews?id=SYLB10,SYDT10");                // 2、创建Request对象;        let urlRequest:URLRequest = URLRequest(url:url);                // 3、发起NSURLConnection连接        let conn:NSURLConnection? = NSURLConnection(request:urlRequest,delegate:self)        conn?.schedule(in: .current, forMode: .defaultRunLoopMode)        conn?.start()    }}// MARK - NSURLConnectionDataDelegateextension ViewController:NSURLConnectionDataDelegate{        func connection(_ connection: NSURLConnection, willSend request: URLRequest, redirectResponse response: URLResponse?) -> URLRequest? {                //发送请求        return request;    }        func connection(_ connection: NSURLConnection, didReceive response: URLResponse) {                //接收响应    }        func connection(_ connection: NSURLConnection, didReceive data: Data) {                //收到数据        self.jsonData.append(data);    }        func connection(_ connection: NSURLConnection, needNewBodyStream request: URLRequest) -> InputStream? {        //需要新的内容流        return request.httpBodyStream;    }        func connection(_ connection: NSURLConnection, didSendBodyData bytesWritten: Int, totalBytesWritten: Int, totalBytesExpectedToWrite: Int) {        //发送数据请求    }        func connection(_ connection: NSURLConnection, willCacheResponse cachedResponse: CachedURLResponse) -> CachedURLResponse? {        //缓存响应        return cachedResponse;    }        func connectionDidFinishLoading(_ connection: NSURLConnection) {        //请求结束        //let jsonStr = String(data: self.jsonData as Data, encoding:String.Encoding.utf8);        //print(jsonStr)        do {            let dic = try JSONSerialization.jsonObject(with: self.jsonData as Data, options: JSONSerialization.ReadingOptions.allowFragments)            print(dic)        } catch let error{            print(error.localizedDescription);        }    }}
View Code

 

转载地址:http://swkml.baihongyu.com/

你可能感兴趣的文章
shell 中 2>&1 的使用
查看>>
Oracle的rownum原理和使用(整理几个达人的帖子)
查看>>
json_encode详解,转义
查看>>
真正的人工智能离我们有多远
查看>>
页面制作部分之PS切图
查看>>
ThinkPhp学习11
查看>>
C#:Md5和Sha1两种加密方式
查看>>
linux -- ubuntuserver 安装图形界面
查看>>
阅读小记3(《C编程专家》)
查看>>
linux cmd
查看>>
VS2010中的调试技巧
查看>>
[译] 一、为何要推出AppCoda系列?
查看>>
HDU4685 Prince and Princess 完美搭配+良好的沟通
查看>>
Spring AOP在pointcut expression解析表达式 并匹配多个条件
查看>>
建立完整的单向动态链表(包括初始化、创建、插入、删除、查找、销毁、输出)...
查看>>
如果有一天你没有了动力,可以看看
查看>>
选择算法
查看>>
反射获取指定类型
查看>>
springJDBC一对多关系,以及Java递归,jsp递归的实现
查看>>
Codeforces Gym 100733A Shitália 计算几何
查看>>