今天的重点是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