网络请求
网络请求是建立在 URL Session 上面的网络库。
-
对 URL Session 进行控制,请求可以是极其简单也可以是复杂的。
-
基于操作队列构建。
- 提供控制服务质量的能力。
- 提供处理重复请求发送的选项。
-
为您处理解析,根据指定的类型。
- CSV、JSON、RAW DATA、CODABLE、CACHEPATH、SUCCESS
-
处理尝试次数,如果没有达到 200...299,将自动尝试请求 3 次。
-
易于继承以处理恢复过期的身份验证令牌/会话。
- 如果 API 返回 401,将由该类处理,一旦恢复,将重置尝试次数并重新请求。
示例代码 基础
import NetworkRequest
// Parses result from API parsed into JSON
NetworkRequest(endpoint: "https://github.com").resultJSON { json in
guard let json = json else { return }
print(json)
}
// Parses result from API into a array of strings
NetworkRequest(endpoint: "https://github.com").resultCSV(qos: .userInteractive) { lines in
guard let lines = lines else { return }
print(lines)
}
// Returns raw data result from API, for you Codable Fans
NetworkRequest(endpoint: "https://github.com").resultData(qos: .userInitiated) { data in
guard let data = data else { return }
print(data)
}
// Returns error == nil if HTTP Status code is in range 200...299
NetworkRequest(endpoint: "https://github.com").resultSuccess(qos: .background) { error in
guard error == nil else { return }
print("Success")
}
// Returns cached file path
NetworkRequest(endpoint: "https://github.com").resultCachedFilePath(qos: .utility) { pathUrl in
guard let pathUrl = pathUrl else { return }
print(pathUrl)
}
// Returns codable type
NetworkRequest(endpoint: "www.google.com").resultModel(asType: [Foo].self, qos: .background) { foos in
guard let foos = foos else { return }
print(foos)
}
私有队列与全局队列
// You can also set you own queue to be passed into the NetworkRequest Result
let bestQueue = ZOperationQueue(queueName: "bestYetQueue")
NetworkRequest(endpoint: "www.google.com").resultModel(asType: [Foo].self,
qos: .background,
queue: bestQueue) { foos in
guard let foos = foos else { return }
print(foos)
}
If you don't pass in your own queue it will default to a single "sharedQueue"
可用参数
这些示例非常基础,如果您需要更多控制,可以选择自定义 URL Session。以下是网络请求的初始化参数
///
/// - parameter endpoint: The url endpoint
/// - parameter equivelanceId: The ID used to check for duplicate operation entries
/// - parameter httpMethod: GET,POST,PUT,DELETE
/// - parameter sessionType: URL Session type: Ephemeral, Binary, JSON
/// - parameter taskType: URL Session Task Type: DataTask, UploadTask, DownloadTask
/// - parameter payload: Add to POST HTTP methods
/// - parameter params: Parameters to add to the URL endpoint
/// - parameter headers: Additional headers that can be added to a url session
///
NetworkRequest(
endpoint: "UrlEndpoint",
equivelanceId: "UniqueID",
httpMethod: .GET,
sessionType: .json,
taskType: .dataTask,
payload: Any,
params: [:],
headers: [:])
处理依赖
let firstReq = NetworkRequest(endpoint: "http://github.com").resultJSON { json in
print("First operation executed")
}
let secReq = NetworkRequest(endpoint: "www.test.com").resultSuccess(dependentOnOperations: [firstReq]) { errorString in
print("Second to be executed")
}
let doneBlock = BlockOperation {
print("Executed when both operations are finished")
}
doneBlock.addDependency(secReq)
ZOperationQueue.sharedQueue.addOperation(doneBlock)
处理文件夹中图片缓存
此代码处理从提供的端点获取图片。此方法将在FileManager中缓存图片。
NetworkRequest(endpoint: "www.google.com").resultImage(docCacheType: .cache) { imageData in
guard let imageData = imageData else { return }
print(imageData)
}
// You can clear the whole cache folder with this method.
NetworkRequest.clearCacheImagesFolder()
添加认证
- 注意:您当然可以在headers参数中添加认证头部,但谁喜欢一遍又一遍地重写代码呢?
假设您想为每个API调用添加一个授权头部,只需SubClass网络请求并重写这两个方法。 - 然后,认证头部将自动添加,如果收到401,将为您处理重新认证。
import NetworkRequest
class AuthNetworkRequest: NetworkRequest {
// Restore Session logic
override func restoreSession(completion: @escaping (_ success: Bool)->Void) {
NetworkRequest(endpoint: "https://www.Restoresession.com").resultSuccess { error in
if let error = error {
print(error.localizedDescription)
completion(false)
} else {
completion(true)
}
}
}
// Get your local saved auth token to pass into headers of all `AuthNetworkRequest` objects
override func getAuthorizationToken() -> String {
return "AuthToken"
}
}
// Then use this class just like you would the `NetworkRequest` class
AuthNetworkRequest(endpoint: "www.google.com").resultSuccess { error in
guard error == nil else { return }
print("success")
}
安装
Cocoa Pods
在您的PodFile
中添加以下示例的pod 'ZZNetworkRequest'
。
use_frameworks!
target 'InsertAppNameHere' do
pod 'ZZNetworkRequest'
end
Carthage
在您的Cartfile
中指定
github "zsteed/NetworkRequest" ~> 1.0.9
访问 https://github.com/Carthage/Carthage
了解如何设置Carthage的更多信息。