Alamofire 的简单封装
2018-10-29 本文已影响24人
S大偉
这里简单的介绍一下Alamofire,同时将简单的分装分享给大家
首先给大家一手资料,免得大家东找西找,等再次使用的话又开始盲目的再找一次,然后后面重复很多次,因此建议大家收藏和学习最好从第一手资料开始,免得被误解,如果看不懂可以借鉴别人的分解。
Alamofire 的Github的一首资料,拿到后有些人会发现,唉怎么没有分享怎么使用,哈哈哈,为此再进一步 使用教程,如果感觉还是不够直接,大家可以参考Alamofire框架的使用一基本用法分解,比较详细,如果感觉还是比较困难,那我只能简单分享一下我这里的封装,为此大家借鉴一下,如果更好的方法还望推荐,谢谢!
【Model】
import UIKit
import Alamofire
class NetworkModel: NSObject {
var urlString:String! = ""
var methodType:HTTPMethod! = .get
var parameters:[String: String]?
var isAnimation:Bool = true
}
【Alamofire封装】其实简单的APP足够用啦
import UIKit
import Alamofire
class NetworkManager: NSObject {
var alamofire:SessionManager?
}
extension NetworkManager {
//单例
static let sharedNetworkManager: NetworkManager = {
let share = NetworkManager()
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 10 //时间超时
share.alamofire = Alamofire.SessionManager(configuration: configuration)
return share
}()
//方法
func requestData(urlString:String, methodType:HTTPMethod, parameters:[String: String]?, finished:@escaping (_ result: AnyObject?, _ error: NSError?) -> ()) {
self.alamofire?.request(urlString, method: methodType, parameters: parameters, encoding: URLEncoding.default)
.responseJSON { response in
if response.result.isSuccess {
debugPrint(response.result)
finished(response.result.value as AnyObject?, nil)
} else {
finished(nil, response.result.error as NSError?)
}
}
}
}
【使用和针对性APP使用】
import UIKit
import Alamofire
import CryptoSwift
import SwiftyJSON
import SwiftProgressHUD
enum NetworkActionType {
case None //空
case LoginIn //登录
}
class JDNetwork: NSObject {
//MARK - 参数
var networkModel:NetworkModel?
var actionType:NetworkActionType = .None
//MARK - 获取接口数据
extension JDNetwork {
func getDataRequest(finished:@escaping (_ result: AnyObject?, _ error: NSError?) -> ()) {
if self.networkModel!.isAnimation {
SwiftProgressHUD.showWait()
}
let urlStr = APPHttp + "/" + self.networkModel!.urlString
NetworkManager.sharedNetworkManager.requestData(urlString: urlStr, methodType: self.networkModel!.methodType!, parameters:self.networkModel!. parameters, finished: {(result, error) in
SwiftProgressHUD.hideAllHUD()
if result != nil && error == nil {
let data = self.handleData(result: result!)
finished(data.0, data.1)
} else {
finished(nil, error)
SwiftProgressHUD.show("网络请求失败", type: SwiftProgressHUDType.fail, autoClear: true, autoClearTime: 2)
}
})
}
}
//MARK: handleData
extension JDNetwork {
func handleData(result:AnyObject) -> (AnyObject?, NSError?){
//返回值
var object:AnyObject?
var error: NSError?
let dict = result as! Dictionary<String, Any>
let code = dict["code"] as? String
//token超时,退出登录
if code == "20000" {
//退出 删除数据
appDelegate.setLoginRootVC()
//提示信息
if let msg = dict["message"] as? String {
SwiftProgressHUD.show(msg, type: SwiftProgressHUDType.fail, autoClear: true, autoClearTime: 2)
}
}
else if code == "00000" { //正常返回
switch self.actionType {
case .None: break
case .LoginIn:
object = JDNetworkData.saveUserInfo(result: result) as AnyObject
}
}
//错误返回
else {
if let msg = dict["message"] as? String {
SwiftProgressHUD.showOnlyText(msg)
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
SwiftProgressHUD.hideAllHUD()
}
error = NSError(domain: msg, code: 9999, userInfo: nil)
}
}
return (object, error)
}
}
【产品Model】
import UIKit
class JDProductModel: JDModel {
var id: Int = 0
var name:String = ""
}
【数据处理】
import UIKit
import SwiftyJSON
class JDNetworkData: NSObject {
//可以使用SwiftyJSON来做类型转换
static func saveUserInfo(result:AnyObject?) -> JDUser? {
let json = JSON(result!)
let dict = json.dictionaryValue["data"]?.dictionaryObject
let user = JDUser.deserialize(from: dict)
return user
}
//也可以使用swift的可选功能进行数据解析
static func handleProductListData(result:AnyObject?) ->(Int,Array<JDProductModel>) {
var products: Array<JDProductModel> = []
var count = 0
if let dict = result as? Dictionary<String, AnyObject> {
if let data = dict["data"] as? Dictionary<String, AnyObject> {
count = data["count"] as! Int
if let list = data["list"] as? Array<Dictionary<String, String>> {
for productDict in list {
let model = JDProductModel.deserialize(from: productDict)
products.append(model!)
}
}
}
}
return (count, products)
}
}
【使用实例】
//MARK: - Network
func loginRequest() {
let network = JDNetwork()
network.actionType = .LoginIn
let model = NetworkModel()
model.methodType = .post
model.urlString = "app/ym/account.ashx"
model.parameters = ["action":"login",
"username":self.loginView.accountView.field.text!,
"pwd":self.loginView.passwordView.field.text!]
network.networkModel = model
network.getDataRequest { (result, error) in
if result != nil {
//数据处理
let user = result! as! JDUser
}
}
}