美文网首页
一、基于URLSession封装网络请求

一、基于URLSession封装网络请求

作者: LeeLeCoder | 来源:发表于2017-04-17 16:09 被阅读0次

1. 前言

在iOS9.0之后,以前使用的NSURLConnection过期,苹果推荐使用NSURLSession来替换NSURLConnection完成网路请求相关操作。

NSURLSession的使用非常简单,先根据会话对象创建一个请求Task,然后执行该Task即可。

NSURLSessionTask本身是一个抽象类,在使用的时候,通常是根据具体的需求使用它的几个子类。关系如下:

2. GET请求

func getWithPath(path: String, paras: Dictionary<String, Any>?, success: @escaping ((_ result: Any) -> ()), failure: @escaping ((_ error: Error) -> ())) {
    var i = 0
    var address: String = path
    
    // 0. Behind the URL stitching parameters
    if let paras = paras {
        for (key, value) in paras {
            if i == 0 {
                address += "?\(key)=\(value)"
            } else {
                address += "&\(key)=\(value)"
            }
            i += 1
        }
    } // end-if
    
    // 1. url
    let url = URL(string: path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
    
    // 2. Establish a connection
    // 2.1 创建会话对象
    let session = URLSession.shared
    // 2.2 根据会话对象创建一个Task(发送请求)
    let dataTask = session.dataTask(with: url!) { (data, urlResponse, error) in
        if let data = data {
            // 4.解析数据
            // mutableContainers: 容器是可变的,转成的结果是可变的类型
            // mutableLeaves: 叶子节点是可变的
            // allowFragments: 允许根节点可以不是Array, Dictionary
            if let result = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) {
                success(result)
            }
        } else {
            failure(error!)
        }
        
    }
    // 3. 执行任务
    dataTask.resume()
}

2. POST请求

func postWithPath(path: String, paras: Dictionary<String, Any>?, success: @escaping ((_ result: Any) -> ()), faliure:@escaping ((_ error: Error) -> ())) {
    var i = 0
    var address: String = ""
    
    // 0. stitching parameters
    if let paras = paras {
        for (key, value) in paras {
            if i == 0 {
                address += "\(key)=\(value)"
            } else {
                address += "&\(key)=\(value)"
            }
            i += 1
        }
    } // end-if
    
    // 1. url
    let url = URL(string: path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
    
    // 2. Establish a request
    
    // 2.1 创建请求
    var urlRequest = URLRequest.init(url: url!, cachePolicy: URLRequest.CachePolicy(rawValue: 0)!, timeoutInterval: 30)
    // 2.2 修改请求方法为POST
    urlRequest.httpMethod = "POST"
    // 2.3 设置请求体
    urlRequest.httpBody = address.data(using: .utf8)
    
    // 3. Establish a connection
    
    // 3.1 创建会话对象
    let session = URLSession.shared
    
    // 3.2 根据会话对象创建一个Task(发送请求)
    let dataTask = session.dataTask(with: urlRequest) { (data, urlResponse, error) in
        if let data = data {
            // 5.解析数据
            if let result = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) {
                success(result)
            }
        } else {
            faliure(error!)
        }
    }
    
    // 4. 执行任务
    dataTask.resume()
}

相关文章

网友评论

      本文标题:一、基于URLSession封装网络请求

      本文链接:https://www.haomeiwen.com/subject/iqmtzttx.html