RXSwift基礎(chǔ)網(wǎng)絡(luò)請(qǐng)求封裝

一、創(chuàng)建項(xiàng)目,集成cocoapods文件

target 'TestAPI' do
    use_frameworks!

    pod 'Alamofire'
    pod 'SwiftyJSON'
    pod 'RxSwift',    '~>4.1.1'
    pod 'RxCocoa',    '~>4.1.1'
    pod 'RxDataSources'
    pod 'Moya/RxSwift', '~> 11.0'
    pod 'NSObject+Rx'
    pod 'SVProgressHUD'
end

這里使用的是Moya、SwiftyJSON、Alamofire進(jìn)行網(wǎng)絡(luò)請(qǐng)求的封裝。

二、配置網(wǎng)絡(luò)請(qǐng)求

//1、根據(jù)Moya要求,網(wǎng)絡(luò)請(qǐng)求需要?jiǎng)?chuàng)建一個(gè)Provider,MoyaProvider需要我們傳入一個(gè)實(shí)現(xiàn)TargetType協(xié)議的對(duì)象,這個(gè)協(xié)議里面包含了請(qǐng)求的路由地址和具體路徑、請(qǐng)求方式等網(wǎng)絡(luò)請(qǐng)求相關(guān)基本信息
let ComSmaManProvider = MoyaProvider<ComSmaManApi>(plugins:[AuthPlugin()])
//路由地址
let KBaseURL = "https://www.douban.com"

public enum ComSmaManApi{
      //基本路由地址get、post請(qǐng)求
      case post(suffixUrl:String, params:[String:Any])
      case get(suffixUrl:String, params:[String:Any])

      //其它路由地址get、post請(qǐng)求
      case otherRequst(baseUrl:String, type:OtherBaseURLRequst)
      public enum OtherBaseURLRequst {
            case post(suffixUrl:String, params:[String:Any])
            case get(suffixUrl:String, params:[String:Any])
      }

}
//實(shí)現(xiàn)TargetType協(xié)議,配置基本信息
extension ComSmaManApi:TargetType{
    //路由地址
    public var baseURL: URL {
          let result = self.getConfigure()
          return URL(string: result.1)!
    }
    //具體地址
    public var path: String {
          let result = self.getConfigure()
          return result.2
    }
    //請(qǐng)求方式get、post
    public var method: Moya.Method {
          let result = self.getConfigure()
          return result.0
    }
    //單元測(cè)試所用
    public var sampleData: Data {
          return "{}".data(using: .utf8)!
    }
    //請(qǐng)求任務(wù)事件(這里附帶上參數(shù))
    public var task: Task {
        //request上傳、upload上傳、download下載
       let result = self.getConfigure()
       return .requestParameters(parameters: result.3, encoding: URLEncoding.default)
    }
    //請(qǐng)求頭
    public var headers: [String : String]? {
        return nil
    }

    private func getConfigure() -> (Moya.Method,String,String,[String:Any]) {
        switch self {
        case .get(suffixUrl: let suffixUrl, params: let params):
            return (.get,KBaseURL,suffixUrl,params)
        case .post(suffixUrl: let suffixUrl, params: let params):
            return (.post,KBaseURL,suffixUrl,params)
        case .otherRequst(baseUrl: let baseUrl, type: let type):
            switch type{
                case .get(suffixUrl: let suffixUrl, params: let params):
                      return (.get,baseUrl,suffixUrl,params)
                case .post(suffixUrl: let suffixUrl, params: let params):
                      return (.post,baseUrl,suffixUrl,params)
             }
        }
    }

}
//當(dāng)需要在header里面添加請(qǐng)求token或者時(shí)間戳等信息時(shí)可以傳入這些配置
struct AuthPlugin: PluginType {

func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
    /*
    var request = request
    UserDefaults.standard.synchronize()
    let accessToken = UserDefaults.standard.value(forKey: "accessToken") as? String
    let timestamp: Int = Int.getTimeStamp()
    request.addValue("\(timestamp)", forHTTPHeaderField: "timestamp")
    if accessToken != nil {
        request.addValue(accessToken!, forHTTPHeaderField: "accessToken")
    }
    print(request.allHTTPHeaderFields)
     */
    return request
}
}

三、配合SwiftyJSONMapper實(shí)現(xiàn)Data轉(zhuǎn)JSON,JSON轉(zhuǎn)Model

1、先創(chuàng)建一個(gè)JSONMappable協(xié)議,讓我們創(chuàng)建的model都遵守這個(gè)協(xié)議
Snip20180810_1.png
2、對(duì)Response和PrimitiveSequence擴(kuò)展
Snip20180810_2.png

Response+SwiftyJSONMapper文件

public extension Response {

/// Maps data received from the signal into an object which implements the ALSwiftyJSONAble protocol.
/// If the conversion fails, the signal errors.
public func map<T: JSONMappable>(to type:T.Type) throws -> T {
    let jsonObject = try mapJSON()
    
    guard let mappedObject = T(fromJson: JSON(jsonObject)) else {
        throw MoyaError.jsonMapping(self)
    }
    
    return mappedObject
}

/// Maps data received from the signal into an array of objects which implement the ALSwiftyJSONAble protocol
/// If the conversion fails, the signal errors.
public func map<T: JSONMappable>(to type:[T.Type]) throws -> [T] {
    let jsonObject = try mapJSON()
    
    let mappedArray = JSON(jsonObject)
    let mappedObjectsArray = mappedArray.arrayValue.flatMap { T(fromJson: $0) }
    
    return mappedObjectsArray
}

}

extension Response {

@available(*, unavailable, renamed: "map(to:)")
public func mapObject<T: JSONMappable>(type:T.Type) throws -> T {
    return try map(to: type)
}

@available(*, unavailable, renamed: "map(to:)")
public func mapArray<T: JSONMappable>(type:T.Type) throws -> [T] {
    return try map(to: [type])
}
}

PrimitiveSequence+SwiftyJSONMapper文件

/// Extension for processing Responses into Mappable objects through ObjectMapper
extension PrimitiveSequence where TraitType == SingleTrait, ElementType == Response {

/// Maps data received from the signal into an object which implements the ALSwiftyJSONAble protocol.
/// If the conversion fails, the signal errors.
public func map<T: JSONMappable>(to type: T.Type) -> Single<T> {
    return flatMap { response -> Single<T> in
        return Single.just(try response.map(to: type))
    }
}

/// Maps data received from the signal into an array of objects which implement the ALSwiftyJSONAble protocol.
/// If the conversion fails, the signal errors.
public func map<T: JSONMappable>(to type: [T.Type]) -> Single<[T]> {
    return flatMap { response -> Single<[T]> in
        return Single.just(try response.map(to: type))
    }
}
}
3、創(chuàng)建model
import SwiftyJSON
struct Douban: JSONMappable{
var channels :[Channel]?
init(fromJson json: JSON) {
    channels = json["channels"].arrayValue.map({Channel(fromJson: $0)})
}
}

struct Channel: JSONMappable {
var name :String?
var nameEn :String?
var channelId :String?
var seqId :String?
var abbrEn :String?

init(fromJson json: JSON) {
    name = json["name"].stringValue
    nameEn = json["nameEn"].stringValue
    channelId = json["channel_id"].stringValue
    seqId = json["seqId"].stringValue
    abbrEn = json["abbrEn"].stringValue
}
}

struct Playlist:JSONMappable {

var r :Int!
var isShowQuickStart: Int!
var song:[Song]!

init(fromJson json: JSON) {
    r = json["r"].intValue
    isShowQuickStart = json["is_show_quick_start"].intValue
    song = json["song"].arrayValue.map({Song(fromJson: $0)})
}

}

struct Song:JSONMappable {
var title: String!
var artist: String!
init(fromJson json: JSON) {
    title = json["title"].stringValue
    artist = json["artist"].stringValue
}
}
4、在viewcontroller中利用ComSmaManProvider請(qǐng)求數(shù)據(jù)
  let data = ComSmaManProvider.rx.request(.get(suffixUrl: "/j/app/radio/channels", params: [:]))
        .map(to: Douban.self)  //轉(zhuǎn)換成model
        .map{$0.channels ?? []} //獲取數(shù)組channels作為tableview的數(shù)據(jù)源
        .asObservable()
    //將數(shù)據(jù)綁定到tableview上
    data.bind(to: tableView.rx.items){ (tableView,row,element) in
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
        cell.textLabel?.text = element.name
        cell.accessoryType = .disclosureIndicator
        return cell
    }.disposed(by: disposeBag)
5、最終效果
Snip20180810_3.png

四、在實(shí)際開(kāi)發(fā)項(xiàng)目中,我們都與后臺(tái)約定一個(gè)數(shù)據(jù)返回成功的標(biāo)識(shí),比如status為1是成功,0為失敗等等其他狀態(tài)。

創(chuàng)建ResponseMapper文件,內(nèi)容如下

let RESULT_CODE = "status"
let RESULT_DATA = "data"


enum XYRequestStatus:String {
    case RequstSuccess = "200"
    case RequstError
}


enum XYError : Error {
    case noRepresentor
    case notSuccessfulHTTP
    case noData
    case couldNotMakeObjectError
    case bizError(resultCode: String?, resultMsg: String?)
}


extension Observable{

    private func resultFromJSON<T:JSONMappable>(jsonData:JSON,classType:T.Type) -> T? {
    return T(fromJson: jsonData)
}

func mapResponseToObj<T:JSONMappable>(type:T.Type) -> Observable<T?> {
    return map{ representor in
        guard let response = representor as? Moya.Response else{
            throw XYError.noRepresentor
        }
        guard ((200...209) ~= response.statusCode) else{
            throw XYError.notSuccessfulHTTP
        }
        
        let json = try? JSON.init(data: response.data)
        if let code = json?[RESULT_CODE].string{
            if code == XYRequestStatus.RequstSuccess.rawValue{
                
                return self.resultFromJSON(jsonData: json![RESULT_DATA], classType: type)
            } else {
                
                throw XYError.bizError(resultCode: json?["code"].string, resultMsg: json?["msg"].string)
            }
        }else{
            throw XYError.couldNotMakeObjectError
        }
    }
}

func mapResponseToObjArray<T:JSONMappable>(type:T.Type) -> Observable<[T]> {
    return map{ representor in
        guard let response = representor as? Moya.Response else{
            throw XYError.noRepresentor
        }
        guard ((200...209) ~= response.statusCode) else{
            throw XYError.notSuccessfulHTTP
        }
        
        let json = try? JSON.init(data: response.data)
        
        if let code = json?[RESULT_CODE].string{
            if code == XYRequestStatus.RequstSuccess.rawValue{
                
                var objects = [T]()
                let objectsArray = json?[RESULT_DATA].array
                if let array = objectsArray{
                    for object in array{
                        if let obj = self.resultFromJSON(jsonData: object, classType: type){
                            objects.append(obj)
                        }
                    }
                    return objects
                }else{
                    throw  XYError.noData
                }
                
            }else{
                throw XYError.bizError(resultCode: json?["code"].string, resultMsg: json?["msg"].string)
            }
            
        }else{
            throw XYError.couldNotMakeObjectError
        }
    }
}

}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1、通過(guò)CocoaPods安裝項(xiàng)目名稱項(xiàng)目信息 AFNetworking網(wǎng)絡(luò)請(qǐng)求組件 FMDB本地?cái)?shù)據(jù)庫(kù)組件 SD...
    陽(yáng)明AI閱讀 16,240評(píng)論 3 119
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫(kù)、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,838評(píng)論 4 61
  • 談自然療法似乎是件很抽象的事,然而對(duì)于2015年帶著“做自然療法信差”使命而誕生的平衡族健康科技公司而言,這是一件...
    平衡族閱讀 347評(píng)論 0 0
  • 有時(shí)候會(huì)莫名的有些小情緒,以前一個(gè)人的時(shí)候喜歡忍者,所以在別人眼中我一直都是一個(gè)很堅(jiān)強(qiáng)很倔強(qiáng)的小姑娘,因?yàn)椤N?..
    會(huì)飛的龍貓貓閱讀 250評(píng)論 0 0
  • 今日事件 1.服務(wù)簽約產(chǎn)業(yè)空間站站長(zhǎng)組場(chǎng)邀約 2.確定一個(gè)產(chǎn)業(yè)空間站一個(gè)廠家,明日簽約 3.學(xué)習(xí)寧?kù)o遠(yuǎn)導(dǎo)師的產(chǎn)業(yè)生...
    全息心空間閱讀 158評(píng)論 0 0

友情鏈接更多精彩內(nèi)容