今天的重點是UIWebView、NSURLSession、JSon。php
網絡編程聯網準備:一、在Info.plist中添加AppTransportSecurity類型Dictionary;二、在AppTransportSecurity下添加AllowArbitaryLoads類型Boolean。web
若是僅僅是查詢數據,建議使用GET;若是是增刪改數據,建議用POST。編程
使用第三方框架:Alamofire——著名的AFNetworking網絡基礎庫。json
UIWebView的使用:swift
加載顯示網頁:api
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序列化後的結果:session
第一種NSURLConnection(爲了得到數據,必定要讓類遵循NSURLConnectionDataDelegate):app
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的步驟:
而真正的使用,有兩種方法:
// // 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() //執行任務:最關鍵的一步,必定要記住 } }
// // 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