pod 文件
target 'MYShopping' do
Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
pod 'Alamofire'
pod 'HandyJSON'
pod 'AlamofireImage'
pod 'Moya'
pod 'SwiftyJSON'
end
Alamofire 网络请求的
HandyJSON json 转模型
AlamofireImage 图片请求
Moya 内部使用 Alamofire 网络请求
SwiftyJSON 一个好用的json 工具
模型文件
import Foundation
import HandyJSON
import SwiftyJSON
class SongModel :HandyJSON{
var id : Int?
var ftype : Int?
var name:String?
var rUrl: String?
var album = [String: Any]()
required init(){
}
}
网络请求文件 (网络请求封装)
import Foundation
import Alamofire
import Moya
import SwiftyJSON
public class CJHttpTool {
/// 使用Moya的请求封装
///
/// 文件图片上传
/// - Parameters:
/// - target:
/// - success: 成功
/// - fail: 失败
/// - progressClosure: 进度
public class func upLoad<T:TargetType>(_ target:T,success:@escaping((JSON)->Void),fail:((Int?,String)->Void)?,progressClosure:((Float)->Void)?){
let provider = MoyaProvider<T>(plugins: [
RequestHandlingPlugin(),
// networkLoggerPlugin
])
provider.request(target,
callbackQueue: DispatchQueue.main,progress: { progress in
print(progress)
},completion: { result in
switch result{
case let .success(response):
let resObject = try? response.mapJSON()
print(response)
case let .failure(error):
print(error)
}
})
/// - Parameters:
/// - target: 请求API,TargetType里的枚举值
/// - success: 成功的回调
/// - error: 连接服务器成功但是数据获取失败
/// - failure: 连接服务器失败
public class func request<T: TargetType>(_ target: T, success: @escaping((JSON) -> Void), failure: ((Int?, String) ->Void)?) {
let provider = MoyaProvider<T>(plugins: [
RequestHandlingPlugin(),
// networkLoggerPlugin
])
if (!isNetwork()) {
failureHandle(failure: failure, stateCode: -1009, message: "网络不可用")
return
}
provider.request(target) { result in
switch result {
case let .success(response):
do {
// *********** 这里可以统一处理错误码,弹出提示信息 ***********
let resObject = try? response.mapJSON()
let responseObject = JSON(resObject ?? "")
print(responseObject)
let code = responseObject["code"].intValue
let msg = String(describing: responseObject["msg"])
switch (code) {
case 200 :
// 数据返回正确
success(responseObject)
case 401:
// 请重新登录
failure!(code,msg)
alertLogin(msg)
default:
// 其他错误
failureHandle(failure: failure, stateCode: code, message: msg)
}
}
case let .failure(error):
let statusCode = error.response?.statusCode ?? 1000
let message = "请求出错,错误码:" + String(statusCode)
failureHandle(failure: failure, stateCode: statusCode, message: error.errorDescription ?? message)
}
}
// 错误处理 - 弹出错误信息
func failureHandle(failure: ((Int?, String) ->Void)? , stateCode: Int?, message: String) {
showLoading(message)
failure?(stateCode ,message)
}
// 登录弹窗 - 弹出是否需要登录的窗口
func alertLogin(_ title: String?) {
// TODO: 跳转到登录页的操作:
}
// 信息弹框
func showLoading(_ message: String) {
// Alert.show(type: .error, text: message)
}
// 基于Alamofire,判断网络是否连接,返回一个布尔值
func isNetwork() -> Bool {
let networkManager = NetworkReachabilityManager()
return networkManager?.isReachable ?? true // 无返回就默认网络已连接
}
}
// MARK: - 打印日志
// static let networkLoggerPlugin = NetworkLoggerPlugin(verbose: true, cURL: true, requestDataFormatter: { data -> String in
// return String(data: data, encoding: .utf8) ?? ""
// }) { data -> (Data) in
// do {
// let dataAsJSON = try JSONSerialization.jsonObject(with: data)
// let prettyData = try JSONSerialization.data(withJSONObject: dataAsJSON, options: .prettyPrinted)
// return prettyData
// } catch {
// return data
// }
// }
}
配置的文件
import Foundation
import Moya
// MARK: - 1、2需要根据项目进行更改
/**
1、配置TargetType协议可以一次性处理的参数
- Todo: 根据自己的需要更改,不能统一处理的移除下面的代码,并在APIManager中实现
**/
public extension TargetType {
var sampleData: Data {
return "{}".data(using: String.Encoding.utf8)!
}
}
//下面的代码不更改
class RequestHandlingPlugin: PluginType {
public func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
var mutateableRequest = request
return mutateableRequest.appendCommonParams();
}
}
//下面的代码不更改
extension URLRequest {
mutating func appendCommonParams() -> URLRequest {
let request = try? encoded(parameters: commonParams, parameterEncoding: URLEncoding(destination: .queryString))
assert(request != nil, "append common params failed, please check common params value")
return request!
}
func encoded(parameters: [String: Any]?, parameterEncoding: ParameterEncoding) throws -> URLRequest {
do {
return try parameterEncoding.encode(self, with: parameters)
} catch {
throw MoyaError.parameterEncoding(error)
}
}
}
以后请求都写在这文件
import Foundation
import Moya
enum MyService{
case getMusic([String:String])
case upLoad(image :Image)
}
extension MyService: TargetType {
var baseURL: URL { URL(string: "https://autumnfish.cn")! }
var path: String {
switch self {
case .getMusic:
return "/search"
case.upwnLoad:
return "api/basic/uploadFile"
}
}
}
var method: Moya.Method {
switch self {
case .getMusic:
case.downLoad:
return .get
}
}
var task: Task {
var parms:[String:Any] = [:]
switch self {
case let .getMusic(parmDicc): // Send no parameters
parms = parmDicc
case let .downLoad(image):
var formDatas = [MultipartFormData]()
let imageData = image.pngData()
let fileName = "iOSPicture).jpg"
let formData = MultipartFormData(provider: .data(imageData!), name: "file", fileName: fileName, mimeType: "multipart/form-data")
formDatas.append(formData)
}
return .uploadMultipart(formDatas)
default:
return .requestPlain
}
return .requestParameters(parameters: parms, encoding: URLEncoding.default)
}
var headers: [String: String]? {
let dicc:[String:Any] = Bundle.main.infoDictionary!
let app_varsion:String = dicc["CFBundleShortVersionString"]! as! String;
let token:String = UserModel.share().token
return ["terminal":"iOS","versionCode":app_varsion,"client":"1", "Authorization":token]
}
}
public func url(_ route: TargetType) -> String {
route.baseURL.appendingPathComponent(route.path).absoluteString
}
// MARK: - Response Handlers
extension Moya.Response {
func mapNSArray() throws -> NSArray {
let any = try self.mapJSON()
guard let array = any as? NSArray else {
throw MoyaError.jsonMapping(self)
}
return array
}
}
实际使用
CJHttpTool.request(MyService.getMusic(["keywords":"去年花开"])) { res in
let songsArray = res["result"]["songs"]
let dic = songsArray[0]
let str = dic["name"]
print(str)
let label = UILabel()
label.text = str.string
let objArr: [SongModel?] = JSONDeserializer<SongModel>.deserializeModelArrayFrom(array: songsArray.arrayObject)!
self.dataArray = objArr.map { model in
print(model)
if let objModel = model{
return objModel
}else{
return SongModel()
}
}
self.tableView .reloadData()
} failure: { code, msg in
}
}
如果不使用moya 也可以 直接使用 Alamofire + handyJson
import Foundation
import Alamofire
import HandyJSON
typealias successBlock = (_ obj:Any)->()
typealias error = (_ error:AFError?)->()
class NetworkManger{
static let shared = NetworkManger()
func getRequest(url:String,parm:Parameters? = nil,method:HTTPMethod, succBlok: successBlock? = nil , err: error? = nil){
AF.request(url,method: method,parameters: parm).responseJSON { response in
switch response.result{
case .success(let obj ):
let dic = obj as! Dictionary<String, Any>
let result = dic["result"] as! Dictionary<String, Any>
// let arry = result["songs"] as! Array[String:Any]
let array = result["songs"] as! Array<Any>
let modesArray = [SongModel].deserialize(from: array)
//
if let sucBlok = succBlok {
sucBlok(modesArray ?? [])
}
case .failure(let errResult):
if let errBlock = err{
errBlock(errResult)
}
print(err)
}
}
}
func getNetRequest(url:String,parm:Parameters? = nil,method:HTTPMethod, succBlok: successBlock? = nil , err: error? = nil){
AF.request(url,method: method,parameters: parm).responseString(completionHandler: {(response :AFDataResponse<String>) in
switch response.result{
case .success(let obj ):
let str = obj
let data = str.data(using: .utf8)
let dic = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)
let dicc = dic as! Dictionary<String, Any>
//
let result = dicc["result"] as! Dictionary<String, Any>
// let arry = result["songs"] as! Array[String:Any]
let array = result["songs"] as! Array<Any>
//
let modesArray = [SongModel].deserialize(from: array)
//
if let sucBlok = succBlok {
sucBlok(modesArray ?? [])
}
case .failure(let errResult):
if let errBlock = err{
errBlock(errResult)
}
print(err)
}
})
}
}