4.处理网络请求URLRequest

三个类:NetworkRequest处理网络请求,JSONParse处理数据转化,JSONRequest请求网络数据并转化
语言:Swift3.0
NetworkRequest

import UIKit

class NetworkRequest: NSObject {
    static func request(url:String, para:String?, result:@escaping (Data?, _ error:String?)->Void){
        if let tmpURL = URL(string:url) {
            var request = URLRequest(url: tmpURL)
            request.httpMethod = "POST"
            let sessionConfig = URLSessionConfiguration.default
            sessionConfig.timeoutIntervalForRequest = 20
            let session = URLSession(configuration: sessionConfig)
            let body = para?.data(using: String.Encoding.utf8)
            let task = session.uploadTask(with: request, from: body, completionHandler: {
                (data, response, error) ->Void in
                if error != nil {
                    result(nil, error!.localizedDescription)
                    return;
                }
                result(data, nil)
            })
            task.resume()
        }else{
            result(nil, "请求地址出错")
        }
    }
}

数据相互转化:json转对象,对象转json

import UIKit

class JSONParse: NSObject {
    /**
     对象转成JSON数据
    **/
    static func toJSON(data:Any)->Data? {
        if JSONSerialization.isValidJSONObject(data) {
            do{
                let result = try JSONSerialization.data(withJSONObject: data, options: [])
                return result
            }catch{
                print("JOSN化失败")
            }
        }
        return nil
    }
    /**
     JSON数据转成对象
    **/
    static func toAny(json:Data)->Any?{
        do{
            let result = try JSONSerialization.jsonObject(with: json, options: [])
            return result
        }catch{
            print("转化失败")
        }
        return nil
    }
}

将两个功能结合起来,获取完json数据结果后转为对象结果返回

import UIKit

class JSONRequest: NSObject {
    /**
     请求返回后将json数据转化为对象数据
    **/
    static fileprivate var result:((Any?, _ error:String?)->Void)?
    static func jsonRequest(url:String, para:String, result:@escaping (Any?, _ error:String?)->Void)->Void{
        self.result = result
        NetworkRequest.request(url: url, para: para, result: requestResult)
    }
    static fileprivate func requestResult(data:Data?, error:String?)->Void{
        if data != nil {
            if let tmp = JSONParse.toAny(json: data!) {
                self.result?(tmp, error)
                return
            }else{
                self.result?(nil, "转化失败")
                return
            }
        }
        self.result?(nil, error)
    }
}

Example:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        JSONRequest.jsonRequest(url: "https://www.gn100.com/interface/login", para: "", result: {
            (data, error) in
            if error != nil {
                print(error!)
            }else{
                print(data!)
            }
        })
        print("ffff")
    }
}

源码:https://github.com/ghyh22/NetworkRequest

你可能感兴趣的:(4.处理网络请求URLRequest)