定义一个协议TargetType来约束网络请求参数,这些参数是Alamofire.request中所需要的参数,当然可以删减和扩展,Method和EncodingType在EndPoint.swift中定义
//Target.swift
import Foundation
public protocol TargetType {
var baseURL: NSURL { get }
var path: String { get }
var method: Method { get }
var parameters: [String: AnyObject]? { get }
var encoding:EncodingType {get}
var headers:[String: String]? {get}
}```
定义一个EndPoint类,将Target和Alamofire进行封装,并用typealias来声明一些在其他类中需要用到Alamofire中的某些类型,这样在其他类中就不需要导入Alamofire这个库,所有关于Alamofire的封装都在EndPoint这个类进行
//EndPoint.swift
import Foundation
import Alamofire
public typealias Method = Alamofire.Method
public typealias ResponseJSON = Response<AnyObject, NSError>
public typealias ResponseData = Response<NSData, NSError>
public typealias ResponseString = Response<String, NSError>
public typealias EncodingType = Alamofire.ParameterEncoding
public class EndPoint<Target:TargetType> {
}
extension EndPoint {
public func request(target:Target) -> Alamofire.Request {
let url = target.baseURL.URLByAppendingPathComponent(target.path).absoluteString
let request = Alamofire.request(target.method, url, parameters: target.parameters, encoding: target.encoding,headers:target.headers )
return request
}
}```
最后创建一个RxZainProvider类,作为网络请求的接口,这里只写了requestJSON,可以用同样的方法扩展requestData,requestString。
//RxZainProvider.swift
import Foundation
import RxSwift
public class RxZainProvider<Target:TargetType> {
}
extension RxZainProvider {
public func requestJSON(target: Target) -> Observable<ResponseJSON> {
return Observable.create({ (observer) -> Disposable in//创建信号源
let request = EndPoint<Target>().request(target)//返回Alamofire.Request类型
//Alamofire中responseJSON方法
request.responseJSON{ (response) in
if let error = response.result.error {
observer.onError(error)
}else {
observer.onNext(response)
observer.onCompleted()
}
}
return AnonymousDisposable{
request.cancel()//请求结束,取消请求
}
})
}
}```
**应用**
创建一个UserAPI.swift
//UserAPI.swift
let UserProvider = RxZainProvider<UserAPI>()
public enum UserAPI {
case Users
}
extension UserAPI: TargetType {
public var baseURL: NSURL { return NSURL(string: "https://rxswift.leanapp.cn")! }
public var path: String {
switch self {
case .Users:
return "/users"
}
}
public var method: Method {
return .GET
}
public var parameters: [String: AnyObject]? {
return nil
}
public var encoding: EncodingType {
return .JSON
}
public var headers: [String : String]? {
return nil
}
}```
let disposeBag = DisposeBag()
override func viewDidLoad() {
UserProvider.request(.Users)
.subscribeNext { print($0.result.value) }
.addDisposableTo(disposebag)
}
网友评论