Swift Moya的简单使用

2020-08-20 16:06:06 浏览数 (2)

Moya是对Alamofire的再次封装。

我们用一张图来对比一下Alamofire和moya的区别:

image

有关Alamofire

为了对Moya有更好的了解。让我们先复习一下Alamofire的用法。

Alamofire 使用一个简单的Get请求 请求城市的实时天气为例子

代码语言:javascript复制
let weatherUrl:String = "http://weatherapi.market.xiaomi.com/wtr-v2/temp/realtime?cityId="
代码语言:javascript复制
func getWeatherInfo() -> Void {
         let parameters = ["cityId":"101040100"];
        Alamofire.request(weatherUrl,method:.get,parameters:parameters,encoding: URLEncoding.default).responseJSON { (response) in
            switch response.result {
            case .success(let json ):
                let jsonDic = json as? NSDictionary
                print(jsonDic! as NSDictionary);
                self.showAlert(weatherDic: jsonDic!)
                
                break
            case .failure(let error):
                print("error:(error)")
                break
            }
        }
    }
Moya的简单实用

封装一个Api Provider

代码语言:javascript复制
//
//  NetworkManager.swift
//  SwiftPlayground
//
//  Created by Destiny on 2020/8/18.
//  Copyright © 2020 Destiny. All rights reserved.
//

import UIKit
import Moya
import HandyJSON

// NetworkAPI就是一个遵循TargetType协议的枚举
let NetworkProvider = MoyaProvider<NetworkAPI>()

enum NetworkAPI {
    // 实时天气
    case realtimeWeather(cityId:String)
}

extension NetworkAPI:TargetType{
    public var baseURL: URL{
        switch self {
        case .realtimeWeather:
            return URL(string: "http://weatherapi.market.xiaomi.com/wtr-v2/temp/realtime?cityId=")!
        }
    }
    
    // 对应的不同API path
    var path: String {
        switch self {
        case .realtimeWeather: return ""
        }
    }
    
    // 请求类型
    public var method: Moya.Method {
        return .get
    }
    
    // 请求任务事件(这里附带上参数)
    public var task: Task {
        var parmeters: [String : Any] = [:]
        switch self {

        case .realtimeWeather(let cityId):
            parmeters = ["cityId":cityId] as [String : Any]
            return .requestParameters(parameters: parmeters, encoding: URLEncoding.default)
        }
    }
    
    // 是否执行Alamofire验证
    public var validate: Bool {
        return false
    }
    
    // 这个就是做单元测试模拟的数据,只会在单元测试文件中有作用
    public var sampleData: Data {
        return "{}".data(using: String.Encoding.utf8)!
    }
    
    // 请求头
    public var headers: [String: String]? {
        return nil
    }
}

网络请求方法

代码语言:javascript复制
/// 基本使用
    func weatherAPI() {
        NetworkProvider.request(NetworkAPI.realtimeWeather(cityId: "101040100")) { result in
            if case .success(let response) = result {
               // 解析数据
                let jsonDic = try! response.mapJSON() as! NSDictionary
                self.showAlert(weatherDic: jsonDic)
            }
        }
        

    }
代码语言:javascript复制
func showAlert(weatherDic:NSDictionary) -> Void {
           let dataDic = weatherDic["weatherinfo"] as! NSDictionary
           let temp = dataDic["temp"] as!String
           let sd = dataDic["SD"] as!String
           
           
           let alertController = UIAlertController(title:"提示",message:"重庆当前温度:(temp)℃,湿度:(sd)",preferredStyle: .alert);
           let canceAction = UIAlertAction(title:"取消",style:.cancel,handler:nil);
           let okAciton = UIAlertAction(title:"确定",style:.default,handler: {
               action in
               print("他点击了确定")
           })
           alertController.addAction(canceAction);
           alertController.addAction(okAciton);
           self.present(alertController, animated: true, completion: nil)
       }

0 人点赞