GitHub: SolarNetworkvue
剛開始寫Swift項目時,用到網絡請求時,毫無疑問,選擇了Moya。但隨着項目的增大,接口愈來愈多,TargetType文件也愈來愈大,尋找某一個接口的參數和其餘配置時,就要在各類Switch中跳來跳去,感到十分煩惱,就算分了多個TargetType,也仍是存在這個問題,因而就乾脆借鑑Moya的優勢,基於Alamofire從新封裝了一個簡單易用的網絡庫,保留了TargetType的服務配置功能,並將接口配置分離成各個獨立的Request,造成一個新的網絡庫SolarNetwork。git
SolarNetwork包括之前幾個類:github
willSend
和 接收到網絡回調後修改回調內容的 didReceive
。因此一個網絡請求的具體流程爲:swift
SLNetwork(SLTarget).request(SLRequest).willSend(SLRequest)
.progressClosure(SLProgress)
.reponseData(OriginalResponse)
.didReceive(SLResponse).decodeTo(Dictionary)
.completionClosure(SLResponse)
.decodeTo(Model: Decodable).dealWithError
複製代碼
大多數狀況下,你只須要關心的是:網絡
SLNetwork(SLTarget).request(SLRequest)
.progressClosure(SLProgress)
.completionClosure(SLResponse)
複製代碼
更多內容請直接到GitHub查看。ide
import SolarNetwork
struct HTTPBinTarget: SLTarget {
var baseURLString: String { return "https://httpbin.org" }
}
let HTTPBinNetwork = SLNetwork(HTTPBinTarget())
複製代碼
import SolarNetwork
//Mark: - GET
class HTTPBinGETRequest: SLRequest {
override func loadRequest() {
super.loadRequest()
self.path = "/get"
}
}
HTTPBinNetwork.request(HTTPBinGETRequest()) { (response) in
if let dictionary = response.dataDictionary {
}
else if let error = response.error {
//show error
}
}
//Mark: - POST
class HTTPBinPOSTRequest: SLRequest {
override func loadRequest() {
super.loadRequest()
self.method = .post
self.path = "/post"
}
/** 利用反射,將屬性自動轉換爲Parameters,不須要本身組裝了 ["userName": "myUserName", "password": "myPassword"] */
let userName = "myUserName"
let password = "myPassword"
}
HTTPBinNetwork.request(HTTPBinPOSTRequest()) { (response) in
if let dictionary = response.dataDictionary {
}
else if let error = response.error {
//show error
}
}
複製代碼
import SolarNetwork
class GitHubDownloadRequest: SLDownloadRequest {
override func loadRequest() {
super.loadRequest()
self.URLString = "http://cdnvue.com/video/rzGHzRA19L/64tBZo"
}
}
let downloadRequest = GitHubDownloadRequest()
GitHubNetwork.download(downloadRequest, progressClosure: { (progress) in
}) { (response) in
}
//若是須要斷點下載此文件,請設置該屬性爲true
downloadRequest.isResume = true
//自定義文件下載完成後的存放路徑,默認爲"/Library/Caches/SLNetwork/Destination/(requestID)"
downloadRequest.destinationURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
複製代碼
import SolarNetwork
class HTTPBinUploadRequest: SLUploadRequest {
override func loadRequest() {
super.loadRequest()
self.path = "/post"
}
}
let uploadRequest = HTTPBinUploadRequest()
uploadRequest.data = data //data to upload
HTTPBinNetwork.upload(uploadRequest, progressClosure: { (progress) in
}) { (response) in
}
複製代碼
Swift 4下,利用Decodable將Json轉爲Modelpost
import SolarNetwork
struct User: Decodable { //Swift 4 Codable
var id: Int
var name: String
var token: String
}
HTTPBinNetwork.request(UserRequest()) { (response) in
if let user = response.decode(to: User.self) {
}
else if let error = response.error {
//show error
}
}
複製代碼