zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    设置为自动启动的WindowService没有开机启动
    Asp.Net部署问题
    MSDTC的折磨
    C# WinForm 边框阴影窗体
    升级DotNetNuke
    常用缩写
    DotNetNuke的升级路径
    日本語文法勉強
    PostSubmitter~在WEB应用程序以外的其他程序里提交Web请求的类
    vue中的锚链接跳转问题
  • 原文地址:https://www.cnblogs.com/quanxi/p/6180720.html
Copyright © 2011-2022 走看看