• Swift3.0:NSURLConnection的使用


    一、介绍

     应用中也不必不可少的会使用网络通信,增强客户端和服务器的交互,可以使用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 - NSURLConnectionDataDelegate
    extension 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 = "U4e13U9898";
                        backreason =                     (
                            "U5185U5bb9U8d28U91cfU5dee",
                            "U65e7U95fbU3001U91cdU590d",
                            "U6807U9898U515a"
                        );
                        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 = "U4e60U8fd1U5e73U201cU4e09U4f1aU201dU5c3cU5c3cU65afU6258";
                    type = topic2;
                },
                            {
            ...........
            ...........
            ...........
    }    

    四、源码:

    //
    //  ViewController.swift
    //  NetWorkTest
    //
    //  Created by 夏远全 on 2017/4/3.
    //  Copyright © 2017年 夏远全. All rights reserved.
    //
    
    /*
     NSURLConnection的使用:
     
     */
    
    import UIKit
    
    class 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 - NSURLConnectionDataDelegate
    extension 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
  • 相关阅读:
    [erlang] Erlang继承(inheritance)
    [python]python 动态调用模块&类&方法
    [mysql]将mysql输入内容保存文件
    [erlang] Erlang TCP(gen_tcp)
    hdu 3350 #define is unsafe && hdu3328 Flipper
    hdu 1690 Bus System
    hdu 1401 Solitaire (双向广搜)
    hdu3172 Virtual Friends (并查集+字典树)
    hdu1426 Sudoku Killer
    hdu3111 Sudoku (精确覆盖解数独 DLX)
  • 原文地址:https://www.cnblogs.com/XYQ-208910/p/6661745.html
Copyright © 2020-2023  润新知