swift5 Alamofire优秀网络框架封装
2022-02-04 本文已影响0人
Johnson_9d92
NetworkManager
import SwiftUI
import Alamofire
//http://localhost:8080/PostListData_recommend_1.json
private let NetworlAPIBaseURL = "http://localhost:8080/"
typealias NetworkRequestResult = Result<Data,Error>
typealias NetworkRequestCompletion = (NetworkRequestResult) -> Void
class NetworkManager{
static let shared = NetworkManager()
var commonHeaders: HTTPHeaders {
["user_id": "123","token": "XXXXXX"]
}
private init(){}
@discardableResult
func fetchingGet(
path: String,
params: Parameters?,
completionCallBack: @escaping NetworkRequestCompletion)
-> DataRequest {
Alamofire.AF.request(NetworlAPIBaseURL + path,
parameters: params,
headers: commonHeaders,
requestModifier: {$0.timeoutInterval = 15})
.responseData { response in
switch response.result {
case let .success(data):
completionCallBack(.success(data))
break
case let .failure(error):
completionCallBack(self.handleError(error))
break
}
}
}
@discardableResult
func fetchingPost(
path: String,
params: Parameters?,
completionCallBack: @escaping NetworkRequestCompletion)-> DataRequest {
Alamofire.AF.request(NetworlAPIBaseURL + path, method: .post,parameters: params,encoding: JSONEncoding.prettyPrinted,headers: commonHeaders,requestModifier: {$0.timeoutInterval = 15})
.responseData { response in
switch response.result {
case let .success(data):
completionCallBack(.success(data))
break
case let .failure(error):
completionCallBack(self.handleError(error))
break
}
}
}
private func handleError(_ error: AFError) -> NetworkRequestResult {
if let underlyingError = error.underlyingError {
let nserror = underlyingError as NSError
let code = nserror.code
if code == NSURLErrorNotConnectedToInternet ||
code == NSURLErrorTimedOut ||
code == NSURLErrorInternationalRoamingOff ||
code == NSURLErrorDataNotAllowed ||
code == NSURLErrorCannotFindHost ||
code == NSURLErrorCannotConnectToHost ||
code == NSURLErrorNetworkConnectionLost {
var userInfo = nserror.userInfo
userInfo[NSLocalizedDescriptionKey] = "网络连接有问题喔~"
let currentError = NSError(domain: nserror.domain, code: code, userInfo: userInfo)
return .failure(currentError)
}
}
return .failure(error)
}
}
NetworkAPI
import SwiftUI
class NetwokAPI {
static func recommendPostList(completion: @escaping (Result<PostList,Error>)->Void){
NetworkManager.shared.fetchingGet(path: "PostListData_recommend_1.json", params: nil) { result in
switch result {
case let .success(data):
let parseResult: Result<PostList,Error> = self.parseDate(data)
completion(parseResult)
case let .failure(error):
completion(.failure(error))
}
}
}
static func createPost(text: String,completion: @escaping (Result<Post,Error>)-> Void) {
NetworkManager.shared.fetchingPost(path: "createPost", params: ["text": text]) { result in
switch result {
case let .success(data):
let parseResult: Result<Post,Error> = self.parseDate(data)
completion(parseResult)
case let .failure(error):
completion(.failure(error))
}
}
}
static func hotPostList(completion: @escaping (Result<PostList,Error>)->Void){
NetworkManager.shared.fetchingGet(path: "PostListData_hot_1.json", params: nil) { result in
switch result {
case let .success(data):
let result: Result<PostList,Error> = self.parseDate(data)
completion(result)
case let .failure(error):
completion(.failure(error))
}
}
}
private static func parseDate<T: Decodable>(_ data: Data)-> Result<T,Error> {
guard let decodeData = try? JSONDecoder().decode(T.self, from: data)else {
let error = NSError(domain: "NetworkAPIError", code: 0, userInfo: [NSLocalizedDescriptionKey: "Can not parse data"])
return .failure(error)
}
return .success(decodeData)
}
}
模型
import Foundation
struct PostList: Codable {
var list: [Post]
}
struct Post: Codable, Identifiable {
let id: Int
let avatar: String // image name
let vip: Bool
let name: String
let date: String // yyyy-MM-dd HH:mm:ss
var isFollowed: Bool
let text: String
let images: [String] // image names
var commentCount: Int
var likeCount: Int
var isLiked: Bool
}
调用
import SwiftUI
import Alamofire
struct ContentView3: View {
@State private var text = ""
var body: some View {
VStack {
Text(text).font(.title)
Button(action: {
self.startLoad()
}) {
Text("Start").font(.largeTitle)
.foregroundColor(.yellow)
}
Button(action: {
self.text = ""
}) {
Text("Clear").font(.largeTitle)
}
}
}
func startLoad() {
NetwokAPI.hotPostList { result in
switch result {
case let .success(list):
self.updateText("Post count \(list.list.count)")
case let .failure(error):
self.updateText(error.localizedDescription)
}
}
}
func updateText(_ text: String) {
self.text = text
}
}