• 工程日记之ChildLost(1):URLSession


    URLSession 是什么

    URL Loading System提供了访问URL资源的系统,提供了访问http/https/自定义URL访问的接口。其中,URLSession实例可以创建多个URLSessionTask实例,完成不同的工作。

    我们可以将URLSession类理解为会话层,用于管理网络接口的创建、维护、删除等等工作,我们要做的工作也只是会话层之后的层。

    • URLSessionDataTask : 一个 数据请求 的 URLSessionTask 的子类,用于数据的请求。
    • URLSessionUploadTask : 是一个 上传数据 的 URLSessionDataTask 的子类。
    • URLSessionDownloadTask : 是一个下载数据 的 URLSessionTask 的子类。
    • URLSessionStreamTask : 是一个双向会话的 URLSessionTask 的子类。

    基础使用

    这里上传下载的都是一个字符串;实际形式是json(需要把NSData转成Json)

    get

                            let url1 = "https://coconutnut.xyz:2019/tumble"
                            let sessionConfigure = URLSessionConfiguration.default
                           // sessionConfigure.httpAdditionalHeaders = ["Content-Type": "application/json"]
                           // sessionConfigure.timeoutIntervalForRequest = 30
                            sessionConfigure.requestCachePolicy = .reloadIgnoringLocalCacheData
                            let session = URLSession(configuration: sessionConfigure)
                             
                            guard let url =  URL(string: url1) else {
                                   return
                            }
                            let url1Request = URLRequest(url: url)
                            let dataTask1 = session.dataTask(with: url1Request) { (data, response, error) in
                             guard data != nil else {return}
                             let str = String(data: data!, encoding: String.Encoding.utf8)
                             // 这里需要再加一个逻辑判断
                              guard let strnow = str else{return}

    最后返回的strnow就是我们要获得的字符串;

    post

    let order = Qumot(value: "1")
        guard let uploadData = try? JSONEncoder().encode(order) else {
            return
        }
        print(uploadData)
      
        let url = URL(string: "https://coconutnut.xyz:2019/qumot")!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        let task = URLSession.shared.uploadTask(with: request, from: uploadData) { data, response, error in
            if let error = error {
                print ("error: (error)")
                return
            }
            guard let response = response as? HTTPURLResponse,
                (200...299).contains(response.statusCode) else {
                print ("server error")
                return
            }
            if let mimeType = response.mimeType,
                mimeType == "application/json",
                let data = data,
                let dataString = String(data: data, encoding: .utf8) {
                print ("got data: (dataString)")
            }
        }
        task.resume()

    使用Delegate

    后台唤醒的地方,可以使用自己写的回调函数

    可以在这些地方用到闭包

    Tasks in a session also share a common delegate object. You implement this delegate to provide and obtain information when various events occur, including when:

    • Authentication fails.

    • Data arrives from the server.

    • Data becomes available for caching.

    If you don’t need the features provided by a delegate, you can use this API without providing one by passing nil when you create a session. 

     另外这是一个异步的接口,你可以一边处理UI一边访问网络

    Like most networking APIs, the URLSession API is highly asynchronous. It returns data to your app in one of two ways, depending on the methods you call:

    • By calling a completion handler block when a transfer finishes successfully or with an error.

    • By calling methods on the session’s delegate as data arrives and when the transfer is complete.

    URLSession的状态

    1. default 

    2. emphemaral : 为了保证用户隐私,不将cookie或者本地cache或者证书持久化

    3. background : 把下载的任务交给System,则即使app已经被terminated此时依然可以被下载,但是当app relaunch的时候要根据identifier重拾这个下载任务并且去retrieve data

    https://developer.apple.com/documentation/foundation/urlsessionconfiguration/1407496-background

     https://developer.apple.com/documentation/foundation/url_loading_system

    https://developer.apple.com/documentation/foundation/url_loading_system/uploading_data_to_a_website

  • 相关阅读:
    两个错误的解决方案
    利用BeautifulSoup爬去我爱我家的租房数据
    使用Docker安装PaddlePaddle安装过程中出现的几个问题
    将博客搬至CSDN
    iOS---实现在屏幕上实时绘图的简单效果---CAShaperLayer和UIBezierPath的简单运用
    举例理解Hibernate的三种状态(转)
    关于hibernate5的映射文件和配置文件改变(转)
    数据库事务四种隔离级别
    使用idea构建Hibernate5项目
    手把手教你如何把java代码,打包成jar文件以及转换为exe可执行文件
  • 原文地址:https://www.cnblogs.com/Plorde/p/12303043.html
Copyright © 2020-2023  润新知