【WIP】iOS 网络通讯

创建: 2018/06/05

 

网络通讯的基础
 App Transport Security

 iOS9以后增加的功能

 只允许满足Apple标准的https通信

 ● 对ATS进行改动的话发布的审查时有可能被询问理由

 ● 设定项目

 

 Allow Arbitrary Loads  允许所有HTTP通信
 NSExceptionDomains  对单独域名进行设定
 NSAllowsArbitraryLoadsInWebContent  仅允许WKWebView, UIWebView进行不安全通信

 

 URLSession

 ● 方法 

 

 dataTask  从URL获取data
 downloadTask  将从URL获得的内容暂时放入文件保存
 uploadTask  上传数据
 resume  开始通信(暂停的话则是继续通信)

 

 

 

class BasicViewController: UIViewController {

    @IBOutlet weak var sampleTextView: UITextView!
    
    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        startSampleRequest()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}

//------------------------------------------------------------------------------------ // action setting //------------------------------------------------------------------------------------ extension BasicViewController { func startSampleRequest() { guard let url = URL.init(string: "http://localhost:3001") else { return } // guard let url = URL.init(string: "https://www.baidu.com/") else { return } let session = URLSession.shared let task = session.dataTask(with: url) { (data, response, error) in if error != nil { print("error: \(String(describing: error))") return } guard let data = data else { return } DispatchQueue.main.async { sleep(2) // 为了测试效果, 暂停2秒 let text = String.init(data: data, encoding: String.Encoding.utf8) self.toggleActivityIndicator(target: self.activityIndicator) self.sampleTextView.text = text } } task.resume() } } //------------------------------------------------------------------------------------ // style setting //------------------------------------------------------------------------------------ extension BasicViewController { private func toggleActivityIndicator(target: UIActivityIndicatorView) { if target.isAnimating { target.stopAnimating() } else { target.startAnimating() } } }

 

 

   
   
   
   
   
通过通讯获取信息
   
   
   
   
   
   
   
   
向API发送信息
   
   
   
   
   
   
   
   
posted @ 2018-06-05 03:12  懒虫哥哥  阅读(138)  评论(0编辑  收藏  举报