iBaseSwift 0.0.51

iBaseSwift 0.0.51

ElegantMediaTeam维护。



 
依赖关系
Alamofire= 4.9.1
SwiftyJSON>= 0
 

iBaseSwift 0.0.51

  • Elegant Media Team

iBaseSwift

用户认证框架,支持本地验证、网络服务、用户会话等认证页面功能

提供的服务

认证服务

Swagger服务

要求

  • iOS 11.0+
  • Xcode 10+

安装

Cocoapods

pod 'iBaseSwift'

使用方法

import iBaseSwift

表单参数项模型 - 查看代码

public struct FormParameterItem {
    
    public var itemType: FormItemType
    public var parameterKey: String
    public var parameterValue: Any?
    public var comparingValue: Any?
    public var characterCount: Int = 0
    public var minCharacterCount: Int = 0
    public var maxCharacterCount: Int = 0
    public var isMandatory: Bool = false
    public var nextItemType: FormItemType? = nil
}

已识别的表单项类型

public enum FormItemType: String {
    case idInt, idString, userRoleInt, userRoleString, firstName, lastName, name, fullName, username, email, otpCode, countryCode, phone, countryCode_phone, address, city, suburb, state, country, zipCode, countryISOCode, latitude, longitude, timezone, dob, _info, summary, _description, about, bio, company, password, confirmPassword, newPassword, confirmNewPassword, other
}
如果某些表单参数项是特定要求的,则将其视为其他

服务如何工作(登录服务)- 查看代码

import Foundation
import UIKit

@objc public protocol iBSLoginDelegate {
    
    @objc optional func validateLoginUser(completion: iBSActionHandler)
    @objc optional func userLoginNetworkRequest(completion: @escaping iBSCompletionHandlerWithData)
}

public class iBSLogin: iBSBase {
    
    public var delegate: iBSLoginDelegate?
    
    public var _initialParams: [String: Any] = [:]
    public var _formItems: [FormParameterItem] = []
    
    
    public init(initialParams: [String: Any], formItems: [FormParameterItem]) {
        _initialParams = initialParams
        _formItems = formItems
    }
    
    
    //MARK: Validate Login User
    public func validateLoginUser(completion: iBSActionHandler) {
        do {
            if try validateForm(formItems: _formItems) {
                completion(true, .Success)
            }
        } catch ValidateError.invalidData(let message) {
            completion(false, message)
        } catch {
            completion(false, .MissingData)
        }
    }
    
    
    //MARK: Proceed with Login User API
    public func userLoginNetworkRequest(completion: @escaping iBSCompletionHandlerWithData) {
        // Check internet connection
        guard Reachability.isInternetAvailable() else {
            completion(false, 503, .NoInternet, nil)
            return
        }
        
        // Init login parameter dictionary
        var loginParameters: [String: Any] = [:]
        
        // Add initial parameters to parameter dictionary
        loginParameters.updateParameterDictionary(values: _initialParams)
        
        // Add other parameters to parameter dictionary
        _formItems.forEach({ item in
            loginParameters.updateParameterDictionary(values: [item.parameterKey: item.parameterValue as Any])
        })
        
        // Remove null value keys from parameter dictionary
        loginParameters = loginParameters.removeNullKeysFromParameterDictionary()
        
        // Login web service call
        AuthAPI.loginPost(body: loginParameters) { (response, error) in
            
            if error != nil {
                // Handle error
                self.hadleErrorResponse(error, completion: { (status, statusCode, message) in
                    completion(status, statusCode, message, nil)
                })
            } else {
                guard let responseJson: AuthUser = response?.payload else {return}
                
                // Set access token to user defaults
                iBSUserDefaults.setAccessToken(token: responseJson.accessToken ?? "")
                
                // Set access token to custom headers at SwaggerAPIClient
                AppConstant.addAccessTokenToSwaggerAPIClientcustomHeaders()
                
                completion(true, 200, response?.message ?? "success", responseJson)
            }
        }
    }
}

使用AppConstant类存储基于API的值(基础URL、API密钥、自定义HTTP头等)- 查看代码

public class AppConstant {
    
    //MARK: Base URL
    public static var baseURL: String = ""
    
    //MARK: RESTful API key
    public static var RESTfulAPIKey: String = ""
    
    //MARK: Google API key
    public static var googleAPIKey: String = ""
    
    //MARK: Custom headers
    public static var customHeaders: [String: String] = [:]
    
    //MARK: Get Updated Custom headers
    public static func getCustomHeaders() -> [String: String] {
        
        customHeaders = ["x-api-key": RESTfulAPIKey, "Accept" : "application/json"]
        
        // Check access token exits
        let accessToken = iBSUserDefaults.getAccessToken()
        
        if !(accessToken.isEmpty) {
            // Add access token to current custom headers
            customHeaders.updateValue(accessToken, forKey: "x-access-token")
        }
        
        return customHeaders
    }
    
    //MARK: Add access token to SwaggerAPIClient Custom headers
    public static func addAccessTokenToSwaggerAPIClientcustomHeaders() {
        
        // Check access token exits
        let accessToken = iBSUserDefaults.getAccessToken()
        
        if !(accessToken.isEmpty) {
            // Add access token to current custom headers
            SwaggerClientAPI.customHeaders.updateValue(accessToken, forKey: "x-access-token")
        }
    }
    
}

使用iBSuserDefaults类在登录/注册后将用户访问令牌存储到Standard UserDefaults中,因为几乎所有的其他网络服务都需要用当前登录用户进行认证,以便与后端/网络服务发送或检索数据 - 查看代码

public struct iBSUserDefaults {
    
    public static let shared = UserDefaults.standard
    
    //MARK: Set FCM token
    public static func setFCMToken(token: String) {
        shared.set(token, forKey: "FCM_TOKEN")
        shared.synchronize()
    }
    
    //MARK: Get FCM token
    public static func getFCMToken() -> String {
        if let token = shared.string(forKey: "FCM_TOKEN") {
            return token
        }
        return ""
    }
    
    //MARK: Set access token
    public static func setAccessToken(token: String) {
        shared.set(token, forKey: "ACCESS_TOKEN")
        shared.synchronize()
    }
    
    //MARK: Get access token
    public static func getAccessToken() -> String {
        if let token = shared.string(forKey: "ACCESS_TOKEN") {
            return token
        }
        return ""
    }
    
    //MARK: Remove access token
    public static func removeAccessToken() {
        shared.object(forKey: "ACCESS_TOKEN")
        shared.synchronize()
    }
}

在成功登录/注册后,将访问令牌保存到Standard UserDefaults中,以及按照以下方式从Standard UserDefaults中删除用户本地保存的访问令牌

public static func setAccessToken(token: String) // Save after login / regiter
public static func getAccessToken() -> String // Required to make authorization for user session based services
public static func removeAccessToken() // Remove after logout