iOS網絡編程


今天的重點是UIWebView、NSURLSession、JSon。

網絡編程聯網准備:1、在Info.plist中添加AppTransportSecurity類型Dictionary;2、在AppTransportSecurity下添加AllowArbitaryLoads類型Boolean。

如果僅僅是查詢數據,建議使用GET;如果是增刪改數據,建議用POST。

使用第三方框架:Alamofire——著名的AFNetworking網絡基礎庫。

UIWebView的使用:

加載顯示網頁:

class ViewController: UIViewController, UIWebViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        let webView = UIWebView(frame: UIScreen.main.bounds)
        let url = URL(string: "http://www.cnblogs.com/quanxi")
        let request = URLRequest(url: url!)
        webView.loadRequest(request)
        webView.delegate = self
        
        self.view.addSubview(webView)
    }
}

整個過程中,有一些方法:

    //連接改變時
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        return true
    }
    //UIWebView加載完成時調用,而無論鏈接是否正確
    func webViewDidStartLoad(_ webView: UIWebView) {
        print("===hello")
    }

網絡操作

首先給出一個JSON測試的接口地址:http://mapi.damai.cn/proj/HotProj.aspx?CityId=0&source=10099&version=30602。下面是用Jason.app序列化后的結果:

第一種NSURLConnection(為了獲得數據,一定要讓類遵循NSURLConnectionDataDelegate):

  1. 首先創建請求對象:var request = NSURLRequest(url: URL(string: "http://www.sina.com")!)。
  2. 創建網絡連接的對象:_ = NSURLConnection(request: req as URLRequest, delegate: self),用這個對象來獲得數據。
    然后有如下方法可在整個網絡請求的過程中調用。
extension ViewController: NSURLConnectionDataDelegate {
    //連接網絡,連接成功則調用
    func connection(_ connection: NSURLConnection, didReceive response: URLResponse) {
        let res = response as! HTTPURLResponse
        print("===\(res.statusCode)")
    }
    //連接成功,后服務器請求數據
    func connection(_ connection: NSURLConnection, didReceive data: Data) {
        print("===\(data)")
        downloadData.append(data)   //var downloadData = NSMutableData()
    }
    //http請求結束后,對數據的處理
    func connectionDidFinishLoading(_ connection: NSURLConnection) {
        //此時downloadData代表了所有的數據
        //解析為Json數據
        let dict = try! JSONSerialization.jsonObject(with: downloadData as Data, options: .allowFragments) as! NSDictionary
        let list = dict["list"] as! NSArray
        print("===\(dict)")
        for d in list {
            var model = Model()
            let di = d as! NSDictionary
            model.Name = di.object(forKey: "Name") as! String
            model.venName = di.object(forKey: "VenName") as! String
            model.showTime = di.object(forKey: "ShowTime") as! String
            dataSource.add(model)
        }
    }
    
}

第二種,現在更推崇使用NSURLSession(就必須使用到NSURLSessionTask):

NSURLSessionTask和其子類的關系:

使用NSURLSession的步驟:

  1. 獲得會話對象Session的實例
  2. 再通過該實例,創建各種task
  3. 然后編寫好task,就可以執行task了。

而真正的使用,有兩種方法:

  1. 使用URLRequest對象
    //
    //  ViewController.swift
    //  k
    //
    //  Created by apple on 16/12/30.
    //  Copyright © 2016年 liuzhenbing. All rights reserved.
    //
    
    import UIKit
    
    class ViewController: UIViewController, UIWebViewDelegate {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            let url = URL(string: "http://mapi.damai.cn/proj/HotProj.aspx?CityId=0&source=10099&version=30602")
            let request = URLRequest(url: url!)
            
            //獲得會話對象Session的實例
            let session = URLSession.shared
            //再創建各種需要的task
            let dataTask = session.dataTask(with: request) {
                (data, response, error) in
                var dict: NSDictionary? = nil
                if error == nil {
                    do {
                        dict = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.init(rawValue: 0)) as? NSDictionary
                    } catch {}
                    //下面就是JSON的具體解析了:可以參照第一種Connection方法
                    let list = dict?["list"] as! NSArray
                    for i in list {
                        let dic = i as! NSDictionary
                        //下面就是最底層,也就是各個具體的字段值
                        print("===\(dic.object(forKey: "Name") as! String)")
                    }
                }
            }
            dataTask.resume()   //執行任務:最關鍵的一步,一定要記住
        }
    }
  2. 直接使用URL對象:
    //
    //  ViewController.swift
    //  k
    //
    //  Created by apple on 16/12/30.
    //  Copyright © 2016年 liuzhenbing. All rights reserved.
    //
    
    import UIKit
    
    class ViewController: UIViewController, UIWebViewDelegate {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            let url = URL(string: "http://mapi.damai.cn/proj/HotProj.aspx?CityId=0&source=10099&version=30602")
            let session = URLSession.shared
            let dataTask = session.dataTask(with: url!) {
                (data, response, error) in
                var dict: NSDictionary? = nil
                if error == nil {
                    do {
                        dict = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.init(rawValue: 0)) as? NSDictionary
                    } catch {}
                    let list = dict?["list"] as! NSArray
                    for i in list {
                        let dic = i as! NSDictionary
                        print("===\(dic.object(forKey: "Name") as! String)")
                    }
                }
            }
            dataTask.resume()
        }
    }

以上代碼都是簡單GET示例,下面給出POST的用法:

//let url = URL(string: "http://www.crs811.com/Json/login.php")!,而且POST必須用request的任務
request.httpMethod = "POST"
request.httpBody = "username=crs811&pwd=123456".data(using: .utf8)

網絡編程的下載主題:

用swift的URLSession來下圖片:

class ViewController: UIViewController, URLSessionDownloadDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        let url = URL(string: "http://images2015.cnblogs.com/blog/1032080/201612/1032080-20161206214110210-418912424.jpg")!
        //session一定要這樣設置,因為要更改下載的代理
        let session = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
        let downLoadTask = session.downloadTask(with: url)
        downLoadTask.resume()
        //以上代碼就已經把想要的文件,下下來了,但是現在,還有兩個問題:要找到文件;這個文件還不能用,因為是.tmp的,要另存為,如.jpg
    }
    
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        let source = location.path
        let save = NSHomeDirectory().appending("/test.jpg")
        print("===\(save)")
        let fileManager = FileManager.default
        do {
            if fileManager.fileExists(atPath: save) {   //如果文件存在,不刪除的話,繼續保存在這里,是會失敗的
                try fileManager.removeItem(atPath: save)
            }
            try fileManager.moveItem(atPath: source, toPath: save)
        } catch {}
    }
    
}

用SDWebImage庫異步加載一張圖片(是UIImageView調用該方法,而不是UIImage):

首先引入庫的時候有幾個選項,記住一定不要選引用,還要記住設置聯網。

@IBOutlet weak var img: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        img?.sd_setImage(with: URL(string: "http://www.crs811.com/wp-content/uploads/2016/11/test.jpg"))
    } 

如果使用cocoaPods來管理庫,也要搭建OC橋才能使用(不知道是不是該庫是OC的緣故)。一個簡單的例程:http://download.csdn.net/detail/leaf_and_wind/9724825


免責聲明!

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



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