我是一个OC开发者,最近的项目进入了混编,所以就写一下有关swift的东西
这里只对最常用的POST和GET的请求做一个简单的封装,决定使用哪一种请求其实只是改变httpMethod的对应值,post请求则httpMethod = "POST",get请求httpMethod="GET"。
post请求往往是在httpBody添加参数,而get请求则一般接在链接Url后面 如:http://apis.eolinker.com/common/xxxx?key=value1&key2=value2
key=value1&key2=value2就是所谓的参数,而post请求则在httpBody中添加key=value1&key2=value2,Url怎不需要后面接问号和任何东西,http://apis.eolinker.com/common/xxxx。
上代码:
这里我创建了一个类 HttpManager封装代码
//定义一个URLSession变量
static var SessionManager = URLSession()
//实现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();
}
实现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
//注意:当前这个闭包是在子线程中执行的,如果想要在这儿执行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转换回原始的url
func urlDecoded() -> String {
return self.removingPercentEncoding ?? ""
}
}
使用方法,这里的接口,我使用的是https://apistore.eolinker.com/#/官网的免费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("原生请求返回数据",dict!)
}) { (error) in
print("请求出错",error)
}
} else
{
AlamofireHttp()
}
第三方Alamofire的简单使用,一笔带过了,教程和官网都有介绍
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("第三方请求的返回数据",response);
}
}