美文网首页
Swift Moya的简单使用

Swift Moya的简单使用

作者: 114105lijia | 来源:发表于2021-12-31 11:34 被阅读0次

    直接上代码:

    LoginAPIManager

    import Foundation
    import Moya
    import SwiftyUserDefaults
    
    //需要实现的接口
    enum LoginAPIManager {
        case login(String?, String?, String?)
        case getUserInfo
    }
    
    extension LoginAPIManager: TargetType {
        var baseURL: URL {
            return URL(string: BaseUrl)!
        }
        
        var method: Moya.Method {
            switch self {
            case .login(_, _, _):
                return .post
            case .getUserInfo:
                return .get
            }
        }
        
        var path: String {
            switch self {
            case .login(_, _, _):
                return login_Url
            case .getUserInfo:
                return My_UserInfo_Role_Url
            }
        }
        
        var headers: [String : String]? {
            var headers = ["Content-Type": "application/json"]
            let token: String = Defaults.token
            if token.count > 0 {
                headers["Authorization"] = "Bearer " + token
            }
            print("--------token = " + "Bearer " + token)
            
            return headers
        }
        
        //任务类型:是否传参,upload/download等都需要使用对应的枚举值
        var task: Task {
            switch self {
            case .login(_, _, _):
                return .requestParameters(parameters: parameters, encoding: parameterEncoding)
            case .getUserInfo:
                return .requestPlain
            }
        }
    }
    
    extension LoginAPIManager {
        //请求参数【这儿进行了枚举,不过只有登录方法需要参数】
        var parameters: [String: String] {
            switch self {
            case let .login(userName, pwd, code):
                var paraDic: [String: String] = [:]
                paraDic.add(key: "username", value: userName)
                paraDic.add(key: "password", value: pwd)
                paraDic.add(key: "code", value: code)
                paraDic.add(key: "platform", value: Platform)
                paraDic.add(key: "regId", value: Defaults.regId)
                
                return paraDic
            case .getUserInfo:
                return [:]
            }
        }
    
        var parameterEncoding: ParameterEncoding {
            return JSONEncoding.default
        }
    

    LoginVM

    import UIKit
    import SwiftyUserDefaults
    import Moya
    
    class LoginVM: BaseVM {
        
        var username: String?
        var password: String?
        var code: String?
        
        let provider = MoyaProvider<LoginAPIManager>()
        
        func loginMoya(success: @escaping () -> ()) {
            ProgressHUD.show(title: "登录中...")
            provider.request(.login(username, password, nil)) { result in
                ProgressHUD.hide()
                switch result {
                    case let .success(response):
                    let jsonDic = try! response.mapJSON() as! NSDictionary
                    
                    if let model = LoginResultModel.deserialize(from: jsonDic)  {
                        
                        Defaults.isLogin = true
                        if String.isNotEmptyStr(str: self.username) {
                            Defaults.userName = self.username!
                        }
                        
                       if let token = model.data?.access_token {
                            Defaults.token = token
                        }
                        
                        success()
                    }
                    
                    case let .failure(moyaError):
                        Alert.show(type: .error, text: moyaError.localizedDescription)
                }
            }
        }
        
        func getUserInfoMoya(success: @escaping () -> ()) {
            
            ProgressHUD.show(title: "查询用户角色...")
            
            provider.request(.getUserInfo) { result in
                ProgressHUD.hide()
                switch result {
                    case let .success(response):
                        let jsonDic = try! response.mapJSON() as! NSDictionary
                        if let model = LoginRoleResultModel.deserialize(from: jsonDic)  {
                            
                            if let user = model.data?.systemUser {
                                UserInfoTool.saveUserInfo(user: user)
                            }
                            if let roles = model.data?.roles {
                                Defaults.roles = roles
                            }
                            
                            success()
                        }
                    
                    case let .failure(moyaError):
                        Alert.show(type: .error, text: moyaError.localizedDescription)
                }
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:Swift Moya的简单使用

          本文链接:https://www.haomeiwen.com/subject/hqegqrtx.html