閑來(lái)無(wú)聊卷哩,研究了一下swift把将,順便寫(xiě)了個(gè)網(wǎng)絡(luò)請(qǐng)求類來(lái)練練手滥朱。
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("網(wǎng)絡(luò)請(qǐng)求錯(cuò)誤 \(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("網(wǎng)絡(luò)請(qǐng)求錯(cuò)誤 \(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)
}
}
}
使用方式也挺簡(jiǎn)單
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 ?? "")
}