The simple and practical moya rxswift

Import tripartite

pod 'Moya/RxSwift', '~> 11.0'
pod 'SwiftyJSON', '~> 4.0' 

Profiles

the UIKit Import 
Import Moya 
Import SwiftyJSON 
Import RxSwift 

// classification request 
public enum {NetTool 
    
    Case Zen 
    Case userProfile (String) 

} 
// MARK: - GET request https://api.github.com/zen https: //api.github. COM / Users / ashfurrow 
//// requested configuration 
Extension NetTool: Moya.TargetType { 
   // the address of the server 
    public the baseURL var: the URL { 
        return the URL (String: "https://api.github.com")! 
    } 
   
    var parameterEncoding: ParameterEncoding { 
        return JSONEncoding.default 
    } 
    // path request 
    public path var: String { 
        Switch Self { 
        Case .zen: 
            return "/ Zen" 
        Case .userProfile (the let name): 
            return "/ Users / \ (name)" 
        } 
    } 
    // methods requested 
    public var Method: Moya.Method { 
        return .get 
    } 
    // This is done in unit testing data, do not control 
    public the sampleData var: the data { 
        return "the Test data" .data (the using: .UTF8)! 
    } 
    task requested time // 
    public var task: Moya.Task { 
        Switch Self { 
        default: 
            return .requestPlain 
        } 
    } 
    / / head configuration request 
    public var headers: [String: String] {? 
        return nil 
    } 
}

 Simple to use, it is recommended json parser to import the three parties, complete analytical

 private let dispose = DisposeBag()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let provider = MoyaProvider<netTool>()
        provider.rx.request(.userProfile("ashfurrow")).subscribe{
            (event) -> Void in
            print("*************\(event)")
            switch event {
            case .success(let response):
                print("?????")
                do {
                                    let info = try response.mapJSON()//返回的数据解析成 JSON
                                    print(info)
                                } catch {
                                   
                                }
                break
            default:
                 break
            }
        }.disposed(by: dispose)
 }

 

Guess you like

Origin www.cnblogs.com/hualuoshuijia/p/12383304.html
Recommended