Moya

导入pod 'Moya',github地址

  • Moya是对Alamofire的二次封装

代码演示

        //实例一
        guard let username = usernameTF.text else {
            print("账户不可为空")
            return
        }
        LGLoginClient.manager.smscode(username: username) { [weak self](smscode) in
            self?.smscodeTF.text = smscode
        }

        //实例二
        LGLoginClient.manager.login(username:usernameTF.text!, password: passwordTF.text!, smscode: smscodeTF.text!)
  • 协议TargetType
//LGLoginAPI.swift
import UIKit
import Moya

public enum LGLoginAPI {
    case login(String, String, String)  // 登录接口
    case smscode(String)                // 登录,发送验证码
    case otherRequest                   // 其他接口,没有参数
}

extension LGLoginAPI: TargetType {

    //服务器地址
    public var baseURL: URL {
        return URL(string:"http://127.0.0.1:5000/")!
    }
    
    // 各个请求的具体路径
    public var path: String {
        switch self {
        case .login:
            return "login/"
        case .smscode:
            return "login/smscode/"
        case .otherRequest:
            return "login/otherRequest/"
        }
    }
    
    // 请求方式
    public var method: Moya.Method {
        switch self {
        case .login:
            return .post
        case .smscode:
            return .post
        default:
            return .get
        }
    }
    
    //这个就是做单元测试模拟的数据,只会在单元测试文件中有作用
    public var sampleData: Data {
        return "{}".data(using: String.Encoding.utf8)!
    }
    
    //请求任务事件(这里附带上参数)
    public var task: Task {
        var param:[String:Any] = [:]

        switch self {
        case .login(let username,let password,let smscode):
            param["username"] = username
            param["password"] = password
            param["smscode"] = smscode
        case .smscode(let username):
            param["username"] = username
        default:
            return .requestPlain
        }
        return .requestParameters(parameters: param, encoding: URLEncoding.default)
    }
    
    //设置请求头
    public var headers: [String: String]? {
        return nil
    }
    
 
}
  • MoyaProvider发起请求
//LGLoginClient.swift
import UIKit
import Moya

class LGLoginClient: NSObject {
    static let manager = LGLoginClient()
    
    //MARK: - 登录事件
    func login(username:String,password:String,smscode:String) {
        let provide = MoyaProvider()
        provide.request(.login(username, password, smscode)) { (result) in
            switch result{
            case let .success(response):
                let _ = LGLoginClient.lgJson(data: response.data)
            case let .failure(error):
                print(error)
            }
        }
    }
    
    //MARK: - 验证码事件
    func smscode(username:String,complete:@escaping ((String) -> Void)) {
        let provide = MoyaProvider()
        provide.request(.smscode(username)) { (result) in
            switch result{
            case let .success(response):
                let dict = LGLoginClient.lgJson(data: response.data)
                complete(dict["smscode"] as! String)
            case let .failure(error):
                print(error)
                complete("")
            }
        }
    }

    //MARK: - 其他事件 - 比如注册
    func otherRequest() {
        let provide = MoyaProvider()
        provide.request(.otherRequest) { (result) in
            switch result{
            case let .success(response):
                let _ = LGLoginClient.lgJson(data: response.data)
            case let .failure(error):
                print(error)
            }
        }
    }

    
   static func lgJson(data:Data?)->([String: Any]){
        guard let data = data else {
            print("data 为空")
            return [:]
        }
        do {
            let dict = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
            print("序列化字典: \(dict)")
            return dict as! ([String : Any])
        } catch {
            print("序列化失败")
            return [:]
        }
    }
}

你可能感兴趣的:(Moya)