1. 程式人生 > >swift3.0請求https封裝工具類(get請求和post請求)

swift3.0請求https封裝工具類(get請求和post請求)

1.首先工具類內部需要遵守URLSessionDataDelegate代理

2.實現代理方法程式碼如下:

func urlSession(_ session:URLSession, didReceive challenge:URLAuthenticationChallenge, completionHandler:@escaping (URLSession.AuthChallengeDisposition,URLCredential?) -> Void) {

guard challenge.protectionSpace.authenticationMethod =="NSURLAuthenticationMethodServerTrust"

else {

return

        }

let credential = URLCredential.init(trust: challenge.protectionSpace.serverTrust!)

        completionHandler(.useCredential,credential)

  }

3.get方法內部實現如下:

// MARK:- getHttps請求

func getHttpsWithPath(path:String,paras: Dictionary<String,Any>?,success:@escaping ((

_ result:Any) -> ()),failure: @escaping ((_ error:Error) -> ())) {

var i =0

var address = path

iflet paras = paras {

for (key,value)in paras {

if i ==0 {

                    address +="?\(key)=\(value)"

                }else {

                    address +="&\(key)=\(value)"

                }

                i += 1

            }

        }

let url =URL(string: address.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlQueryAllowed)!)

print(url!)

let request =URLRequest.init(url: url!)

let session =URLSession.init(configuration:URLSessionConfiguration.default, delegate:self, delegateQueue: OperationQueue.main)

let dataTask = session.dataTask(with: request, completionHandler: {(data,respond,error)in

iflet data = data {

iflet result = try?JSONSerialization.jsonObject(with: data, options: .allowFragments){

DispatchQueue.main.async(execute: {

                        success(result)

                    })

                }

            }else {

DispatchQueue.main.async(execute: {

                    failure(error!)

                })

            }

        })

        dataTask.resume()

    }


4.post方法內部實現如下:

// MARK:- postHttps請求

func postHttpsWithPath(path:String,paras: Dictionary<String,Any>?,success:@escaping ((_ result:Any) -> ()),failure: @escaping ((_ error:Error) -> ())) {

var i =0

var address:String = ""

iflet paras = paras {

for (key,value)in paras {

if i ==0 {

                    address +="\(key)=\(value)"

                }else {

                    address +="&\(key)=\(value)"

                }

                i += 1

            }

        }

let url =URL(string: path)

var request =URLRequest.init(url: url!)

        request.httpMethod ="POST"

        request.httpBody = address.data(using: .utf8)

let session =URLSession.init(configuration:URLSessionConfiguration.default, delegate:self, delegateQueue: OperationQueue.main)

let dataTask = session.dataTask(with: request) { (data, respond, error)in

iflet data = data {

iflet result = try?JSONSerialization.jsonObject(with: data, options: .allowFragments) {

DispatchQueue.main.async(execute: {

                        success(result)

                    })

                }

            }else {

DispatchQueue.main.async(execute: {

                    failure(error!)

                })

            }

        }

        dataTask.resume()

    }


5.給工具類(HCTool)設定單例如下:

staticlet share =HCTool()


6.如何使用post工具類:(定義好路徑path和引數dict即可,可傳Nil)

        let path ="https://10.148.83.228:9876/user/login/user/post/,/post"

let dict = ["phoneNum":"13025672622","password":"111111"]

HCTool.share.postHttpsWithPath(path: path, paras: dict, success: {(result) in

print(result)

        }, failure: {(error) in

print(error)

        })


7.如何使用get工具類(定義好path喝dict兩個引數即可,可傳Nil)

let path ="https://10.148.83.228:9876/user/login/user/post/,/post"

let dict = ["phoneNum":"13025672622","password":"111111"]

HCTool.share.getHttpsWithPath(path: path, paras: dict, success: {(result) in

print(result)

        }, failure: {(error) in

print(error)

        })

8.輸出結果如下,正常:

{

    description = "\U767b\U5f55\U6210\U529f\Uff01";

    result = "S_OK";

    tagObject =     {

        birth = "<null>";

        email = "<null>";

        expProIds =         (

        );

        hobby = "<null>";

        job = "<null>";

        lat = 0;

        locate = "<null>";

        lon = 0;

        phoneNum = 13025672622;

        pwd = "";

        qq = "<null>";

        selfProIds =         (

        );

        sex = 0;

        userId = "b22f0020-17db-49b9-82e3-04619da1adec";

        username = "\U9648\U5927\U7237";

        verifyCode = "";

        verifyTime = "<null>";

        wechat = "<null>";

        weibo = "<null>";

    };

}

10.工具類下載地址:

http://download.csdn.net/detail/aa31140105/9709453