我是一個OC開發(fā)者,最近的項目進入了混編为居,所以就寫一下有關(guān)swift的東西
這里只對最常用的POST和GET的請求做一個簡單的封裝碌宴,決定使用哪一種請求其實只是改變httpMethod的對應(yīng)值,post請求則httpMethod = "POST",get請求httpMethod="GET"蒙畴。
post請求往往是在httpBody添加參數(shù)贰镣,而get請求則一般接在鏈接Url后面 如:http://apis.eolinker.com/common/xxxx?key=value1&key2=value2
key=value1&key2=value2就是所謂的參數(shù),而post請求則在httpBody中添加key=value1&key2=value2膳凝,Url怎不需要后面接問號和任何東西碑隆,http://apis.eolinker.com/common/xxxx。
上代碼:
這里我創(chuàng)建了一個類 HttpManager封裝代碼
//定義一個URLSession變量
static var SessionManager = URLSession()
//實現(xiàn)GET請求
class func GetRequestSession(urlstr:String,parameters:NSDictionary?,Success:@escaping(_ response:Any) ->Void,Fail:@escaping(_ error:NSError) ->Void) -> Void {
var _UrlStr:String = urlstr
if (parameters != nil) {
let JSONArr:NSMutableArray = NSMutableArray()
for key:Any in (parameters?.allKeys)!
{
let JSONString = ("\(key)\("=")\(parameters![key] as! String)")
JSONArr.add(JSONString)
}
let paramStr = JSONArr.componentsJoined(by:"&")
_UrlStr.append("?"+paramStr)
print("請求字符串"+_UrlStr)
}
let _url = URL.init(string:(_UrlStr.urlEncoded()))
var urlRequest = URLRequest.init(url: _url!)
urlRequest.httpMethod = "GET"
let configuration:URLSessionConfiguration = URLSessionConfiguration.default
HttpManager.SessionManager = URLSession(configuration: configuration)
let task = HttpManager.SessionManager.dataTask(with:urlRequest){ (data, response, error) in
if ((error) == nil)
{
if(data == nil)
{
return;
}
let jsonData = try!JSONSerialization.jsonObject(with: data! as Data, options: .mutableContainers)
Success(jsonData);
}
else
{
Fail(error! as NSError)
}
}
task.resume();
}
實現(xiàn)POST請求
class func POSTRequestSession(urlstr:String,parameters:NSDictionary?,Success:@escaping(_ response:Any) ->Void,Fail:@escaping(_ error:NSError) ->Void) -> Void {
let _UrlStr:String = urlstr
let _url = URL.init(string:(_UrlStr.urlEncoded()))
var urlRequest = URLRequest.init(url: _url!)
urlRequest.httpMethod = "POST"
let JSONArr:NSMutableArray = NSMutableArray()
if (parameters != nil) {
for key:Any in (parameters?.allKeys)!
{
let dictStr = "\(key)\("=")\(parameters!.value(forKey: key as! String)!)"
JSONArr.add(dictStr)
}
urlRequest.httpBody = (JSONArr.componentsJoined(by: "&")).data(using: .utf8)
}
let configuration:URLSessionConfiguration = URLSessionConfiguration.default
HttpManager.SessionManager = URLSession(configuration: configuration)
let task = HttpManager.SessionManager.dataTask(with:urlRequest){ (data, response, error) in
//注意:當(dāng)前這個閉包是在子線程中執(zhí)行的蹬音,如果想要在這兒執(zhí)行UI操作必須通過線程間的通信回到主線程
if ((error) == nil)
{
if(data == nil)
{
return;
}
let jsonData = try!JSONSerialization.jsonObject(with: data! as Data, options: .mutableContainers)
Success(jsonData);
}
else
{
Fail(error! as NSError)
}
}
task.resume();
}
}
以下是涉及用到的擴展方法
extension String {
//將原始的url編碼為合法的url
func urlEncoded() -> String {
let encodeUrlString = self.addingPercentEncoding(withAllowedCharacters:
.urlQueryAllowed)
return encodeUrlString ?? ""
}
//將編碼后的url轉(zhuǎn)換回原始的url
func urlDecoded() -> String {
return self.removingPercentEncoding ?? ""
}
}
使用方法上煤,這里的接口,我使用的是https://apistore.eolinker.com/#/官網(wǎng)的免費API祟绊,是查詢天氣用的
get和post使用方法一樣
HttpManager.POSTRequestSession(urlstr:"http://apis.eolinker.com/common/weather/get15DaysWeatherByArea", parameters:["productKey":params.productKey!,"area":params.area!], Success: { (response) in
let dict = response as? NSDictionary
if (dict == nil)
{
return;
}
print("原生請求返回數(shù)據(jù)",dict!)
}) { (error) in
print("請求出錯",error)
}
} else
{
AlamofireHttp()
}
第三方Alamofire的簡單使用楼入,一筆帶過了,教程和官網(wǎng)都有介紹
Alamofire.request("http://apis.eolinker.com/common/weather/get15DaysWeatherByArea", method: .post, parameters: ["productKey":params.productKey!,"area":params.area!], encoding:URLEncoding.default, headers: nil).responseJSON { (response) in
print("第三方請求的返回數(shù)據(jù)",response);
}
}