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 = "\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 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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM