闲来无聊,研究了一下swift,顺便写了个网络请求类来练练手。
import UIKit
import AFNetworking
import Result
import ReactiveSwift
enum request_type: Int {
case GET = 0
case POST = 1
}
class RequestManager: AFHTTPSessionManager {
static let instance: RequestManager = {
let instance = RequestManager()
instance.requestSerializer = AFHTTPRequestSerializer()
instance.responseSerializer = AFHTTPResponseSerializer()
instance.responseSerializer.acceptableContentTypes = ["text/html","application/json","text/plain"]
return instance
}()
//function rac
func netRequest(type:request_type,url:String,param:[String:Any]?) -> Signal<Any, NoError> {
let (signal,observer) = Signal<Any, NoError>.pipe()
let success = { (task: URLSessionDataTask, json: Any)->() in
let data = json as? Data
let str:String = String(data: data!, encoding: String.Encoding.utf8)! as String
observer.send(value: str )
observer.sendCompleted()
}
let failure = { (task: URLSessionDataTask?, error: Error) -> () in
print("网络请求错误 \(error)")
observer.send(value: error)
observer.sendCompleted()
}
guard type == .GET else {
post(url, parameters: param, progress: nil, success: success, failure: failure)
return signal
}
get(url, parameters: param, progress: nil, success: success, failure: failure)
return signal
}
//function block
func request(type: request_type, url: String, param: [String: AnyObject]?, completion: @escaping (AnyObject?) -> ()) {
let success = { (task: URLSessionDataTask, json: Any)->() in
let data = json as? Data
let str:String = String(data: data!, encoding: String.Encoding.utf8)! as String
completion(str as AnyObject?)
}
let failure = { (task: URLSessionDataTask?, error: Error) -> () in
print("网络请求错误 \(error)")
completion(nil)
}
if type == .GET {
get(url, parameters: param, progress: nil, success: success, failure: failure)
} else {
post(url, parameters: param, progress: nil, success: success, failure: failure)
}
}
}
使用方式也挺简单
RequestManager.instance.netRequest(type: request_type.GET, url: url, param: nil).observeResult({ (result:Any) in
print(result)
})
RequestManager.instance.request(type: request_type.GET, url: url, param: nil) { (json:AnyObject?) in
print(json ?? "")
}