使用Objective-C开发的应该非常熟悉AFNetworking这个网络框架。在Swift诞生之后,AFNetworking的作者用Swift来编写一个类似AFNetworking的网络框架,那就是Alamofire!->github.
一直使用Objective-C开发,我来尝试下用Swift进行开发,首先从网络框架入手,对Alamofire进行二次封装。
目前Alamofire的最新版本是5.0.0,还没有5.0的文档 -_-!!!
直接盘它
import UIKit
import Alamofire
import Foundation
typealias FSResponseSuccess = (_ response: String) -> Void
typealias FSResponseFail = (_ error: String) -> Void
typealias FSNetworkStatus = (_ NetworkStatus: Int32) -> Void
typealias FSProgressBlock = (_ progress: Int32) -> Void
@objc enum NetworkStatus: Int32 {
case unknown = -1//未知网络
case notReachable = 0//网络无连接
case wwan = 1//2,3,4G网络
case wifi = 2//wifi网络
}
class FSNetworkRequest: NSObject {
//单例
static let share = FSNetworkRequest()
private var sessionManager: Session?
override init() {
super.init()
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 60
sessionManager = Session.init(configuration: configuration, delegate: SessionDelegate.init(), serverTrustManager: nil)
}
///当前网络状态
private var mNetworkStatus: NetworkStatus = NetworkStatus.wifi
public func getWith(url: String,
params: [String: Any]?,
success: @escaping FSResponseSuccess,
error: @escaping FSResponseFail) {
requestWith(url: url,
httpMethod: 0,
params: params,
success: success,
error: error)
}
public func postWith(url: String,
params: [String: Any]?,
success: @escaping FSResponseSuccess,
error: @escaping FSResponseFail) {
//根绝业务需求变动
//参数拼接url
let url = FSRequestData.share.getUrlAddParams(params: params, url: url)
//数据进行加密
let dic = FSRequestData.share.getReqData(params: params)
requestWith(url: url,
httpMethod: 1,
params: dic,
success: success,
error: error)
}
public func requestWith(url: String,
httpMethod: Int32,
params: [String: Any]?,
success: @escaping FSResponseSuccess,
error: @escaping FSResponseFail) {
//get
if httpMethod == 0 {
manageGet(url: url, params: params, success: success, error: error)
} else {
managePost(url: url, params: params!, success: success, error: error)
}
}
private func managePost(url: String,
params: [String: Any],
success: @escaping FSResponseSuccess,
error: @escaping FSResponseFail) {
//请求头信息
var header = HTTPHeaders()
header.add(name: "dragon-system", value: FSRequestData.share.getHeaderJson())
AF.request(url,
method: .post,
parameters: params,
encoding: URLEncoding.default,
headers: header).responseJSON { (response) in
switch response.result {
case .success:
let json = String(data: response.data!, encoding: String.Encoding.utf8)
success(json ?? "")
case .failure:
let statusCode = response.response?.statusCode
error("\(statusCode ?? 0)请求失败")
debugPrint(response.response as Any)
}
}
}
private func manageGet(url: String,
params: [String: Any]?,
success: @escaping FSResponseSuccess,
error: @escaping FSResponseFail) {
//请求头信息
var header = HTTPHeaders()
header.add(name: "dragon-system", value: FSRequestData.share.getHeaderJson())
AF.request(url,
method: .get,
parameters: params,
encoding: URLEncoding.default,
headers: header).responseJSON { (response) in
switch response.result {
case .success:
let json = String(data: response.data!, encoding: String.Encoding.utf8)
success(json ?? "")
case .failure:
let statusCode = response.response?.statusCode
error("\(statusCode ?? 0)请求失败")
debugPrint(response.response as Any)
}
}
}
/** 上传图片*/
public func postImage(url:String,params:Parameters?,fileConfig:FSFileConfig,progressBlock:@escaping FSProgressBlock,success:@escaping FSResponseSuccess,error:@escaping FSResponseFail){
var header = HTTPHeaders()
header.add(name: "dragon-system", value: FSRequestData.share.getHeaderJson())
header.add(name: "content-type", value: "multipart/form-data")
let url = FSRequestData.share.getUrlAddParams(params: params, url: url)
let dic = FSRequestData.share.getReqData(params: params)
// 默认60s超时
AF.upload(multipartFormData: { multipartFormData in
multipartFormData.append(fileConfig.fileData, withName: fileConfig.name, fileName: fileConfig.fileName, mimeType: fileConfig.mimeType);
if dic.count != 0 {
for (key, value) in dic {
let str:String = value
let _datas:Data = str.data(using: String.Encoding.utf8)!
multipartFormData.append(_datas, withName: key )
}
}
}, usingThreshold: MultipartFormData.encodingMemoryThreshold,fileManager:.default, to: url, method: .post, headers: header, interceptor: nil).responseJSON { (response) in
switch response.result {
case .success:
let json = String(data: response.data!, encoding: String.Encoding.utf8)
success(json ?? "")
case .failure:
let statusCode = response.response?.statusCode
error("\(statusCode ?? 0)请求失败")
debugPrint(response.response as Any)
}
}
}
}
// MARK: 网络状态相关
extension FSNetworkRequest {
///监听网络状态
public func detectNetwork(netWorkStatus: @escaping FSNetworkStatus) {
let reachability = NetworkReachabilityManager()
reachability?.startListening()
reachability?.listener = { [weak self] status in
guard let weakSelf = self else { return }
if reachability?.isReachable ?? false {
switch status {
case .notReachable:
weakSelf.mNetworkStatus = NetworkStatus.notReachable
case .unknown:
weakSelf.mNetworkStatus = NetworkStatus.unknown
case .reachable(.wwan):
weakSelf.mNetworkStatus = NetworkStatus.wwan
case .reachable(.ethernetOrWiFi):
weakSelf.mNetworkStatus = NetworkStatus.wifi
}
} else {
weakSelf.mNetworkStatus = NetworkStatus.notReachable
}
netWorkStatus(weakSelf.mNetworkStatus.rawValue)
}
}
///监听网络状态
public func obtainDataFromLocalWhenNetworkUnconnected() {
self.detectNetwork { (_) in
}
}
}
class FSFileConfig: NSObject {
var fileData : Data
var name : String
var fileName : String
var mimeType : String
override init() {
fileData = Data()
name = ""
fileName = ""
mimeType = ""
}
func initFile(fileData : Data,name : String,fileName : String,mimeType : String) {
self.fileData = fileData
self.name = name
self.fileName = fileName
self.mimeType = mimeType
}
}
实例调用,使用HandyJSON进行解析
func getData() {
struct BaseModel: HandyJSON {
var info : String?
var status : Int?
var data : DataModel?
}
struct DataModel: HandyJSON {
var header : Any?
var video : Any?
var list1 : Any?
var list2 : Any?
var list3 : Any?
}
self.showLoading()
FSNetworkRequest.share.postWith(url: NetworkRequestDefine.URL_index, params: nil, success: { (json) in
self.hideLoading()
let model = JSONDeserializer<BaseModel>.deserializeFrom(json: json)
debugPrint(model!)
}) { (response) in
debugPrint(response)
}
}
func getData1() {
let image = UIImage.init(named: "icon_tabbar_20")
var fileConfig = FSFileConfig.init()
let data = image?.jpegData(compressionQuality: 0.5)
fileConfig.initFile(fileData: data!, name: "img", fileName: "img.jpg", mimeType: "image/jpeg")
FSNetworkRequest.share.postImage(url: NetworkRequestDefine.URL_my_uploadimg_index, params: nil,fileConfig: fileConfig, progressBlock: { (progress) in
}, success: { (response) in
}) { (response) in
debugPrint(response)
}
}