• Swift_网络请求


    一、网络请求步骤

    1. 设置请求url
    2. 设置URLRequest对象,配置请求相关信息
    3. 创建会话配置URLSessionConfiguration
    4. 创建会话URLSession
    5. 创建任务和设置请求回调,并发起请求

    一般通过以上几个步来完成网络请求,当然要根据不同应用场景来配置请求属性。

    二、使用

    1、原生

    json转dic

        //json转dic
        func getDictionaryFromJSONString(jsonString:String) ->NSDictionary{
            let jsonData:Data = jsonString.data(using: .utf8)!
            let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
            if dict != nil {
                return dict as! NSDictionary
            }
            return NSDictionary()
        }

    Get

        func makeLogon() {
            // 构建URL
            let url:URL = URL(string: "https://xxx/xxx/API?xxx")!
            // 发送HTTP请求的的session对象
            let session = URLSession.shared
            // 构建请求request
            var request = URLRequest(url: url)
            request.httpMethod = "GET"
            // 发一个get请求
            let task = session.dataTask(with: request as URLRequest) {(
                data, response, error) in
                
                guard let data = data, let _:URLResponse = response, error == nil else {
                    print("error")
                    return
                }
                let dataString =  String(data: data, encoding: String.Encoding.utf8)
                let dict = self.getDictionaryFromJSONString(jsonString: dataString!)
                print(dict)
            }
            task.resume()
        }
    

    Post

        func makeUpdateCountSheet() {
            // 这里直接使用 jsonString 转成字典,然后转成 Data,将 流 放到 request的 httpBody中, 模拟发送一个http请求
            let jsonString = "{\"Data\":{\"xxx\":\"834\",\"xxx\":[{\"xxx\":[{\"xxx\":\"031019\",\"xxx\":\"ADD\",\"xxx\":\"9\"},{\"xxx\":\"5651G-06920ADBAA\",\"xxx\":\"ADD\",\"xxx\":\"6\"}],\"xxx\":\"xxx\",\"Counted\":true,\"xxx\":true,\"LineNum\":\"1\",\"xxx\":\"235\",\"Quantity\":\"15\"}],\"xxx\":\"\",\"Initials\":\"we\",\"xxx\":true},\"xxx\":\"\"}"
            let dict = self.getDictionaryFromJSONString(jsonString: jsonString)
            print(dict)
            var  jsonData = NSData()
            do {
                 jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) as NSData
            } catch {
                print(error.localizedDescription)
            }
            // 构建URL
            let url:URL = URL(string: "https://xxx/xxx/API?xxx")!
            // session
            let session = URLSession.shared
            // request
            var request = URLRequest(url: url)
            request.httpMethod = "POST"
            // 设置Content-Length,非必须
            request.setValue("\(jsonData.length)", forHTTPHeaderField: "Content-Length")
            // 设置 Content-Type 为 json 类型
            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
            // POST    请求将 数据 放置到 请求体中
            request.httpBody = jsonData as Data
            // 发送请求
            let task = session.dataTask(with: request as URLRequest) {(
                data, response, error) in
    
                guard let data = data, let _:URLResponse = response, error == nil else {
                    print("error")
                    return
                }
                // 返回值 utf8 转码
                let dataString =  String(data: data, encoding: String.Encoding.utf8)
                // 将 jsonString 转成字典
                let dict = self.getDictionaryFromJSONString(jsonString: dataString!)
                print(dict)
            }
            task.resume()
        }

    2、Alamofire 

    3、Moya+Alamofire 

    Moya是一个对Alamofire封装的库,提供简洁的接口供开发者调用,抽象了URL和Parameters来帮助使用者生成urlRequest,最后通过alamofire发起请求。
    具体使用时在Moya和Your App之间加一层Rx,用于处理请求回来的数据

  • 相关阅读:
    WSL 修改默认登录用户为root
    WSL ssh服务自启动
    odoo 获取model的所有字段
    C++类型父类与子类的转换--dynamic_cast(转)
    开源软件/镜像库
    C/C++编译器gcc的windows版本MinGW-w64安装教程(转)
    msys2 环境搭建
    Windows下利用Cygwin搭建C/C++开发环境GCC(转)
    模板类中子类访问父类中的成员需要通过this指针
    C++ 构造函数与this指针
  • 原文地址:https://www.cnblogs.com/liyonghua/p/16143657.html
Copyright © 2020-2023  润新知