轻松实现网络操作
NetOperations 是一个基于 URL Session 的网络库。
-
可以对 URL Session 进行控制,请求可以非常简单或复杂。
-
基于操作队列构建。
-
可以控制服务质量。
-
可以处理重复请求。
-
可以处理操作依赖。
-
根据指定的类型自动处理解析。
-
CSV, JSON, RAW DATA, CODABLE, CACHEPATH, SUCCESS
-
处理尝试次数,如果 200...299 响应未达到,会为您尝试端点 3 次。
-
具有易于子类的功能,可以处理过期身份验证令牌/会话的恢复。
-
如果 API 返回 401,由该类处理,一旦恢复,将重置尝试次数并重试请求
示例代码基本
// import NetOperations
// Parses result from API parsed into JSON
NetworkOperation(endpoint: "https://github.com").resultJSON { json in
print(json!)
}
// Parses result from API into a array of strings
NetworkOperation(endpoint: "https://github.com").resultCSV(qos: .userInteractive) { lines in
print(lines!)
}
// Returns raw data result from API, for you Codable Fans
NetworkOperation(endpoint: "https://github.com").resultData(qos: .userInitiated) { data in
print(data!)
}
// Returns error == nil if HTTP Status code is in range 200...299
NetworkOperation(endpoint: "https://github.com").resultSuccess(qos: .background) { error in
guard error == nil else { return }
print("Success")
}
// Returns cached file path
NetworkOperation(endpoint: "https://github.com").resultCachedFilePath(qos: .utility) { pathUrl in
print(pathUrl!)
}
// Returns codable type
NetworkOperation(endpoint: "www.google.com").resultModel(asType: [Foo].self, qos: .background) { foos in
print(foos!)
}
私有与全局队列
// You can also set you own queue to be passed into the NetworkOperation Result
let bestQueue = NetworkQueue(queueName: "bestYetQueue")
NetworkOperation(endpoint: "www.google.com").resultModel(asType: [Foo].self,
qos: .background,
queue: bestQueue) { foos in
print(foos!)
}
If you don't pass in your own queue it will default to a single "globalQueue"
可用参数
这些示例非常基础,如果您需要更多控制,可以选择自定义 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
///
NetworkOperation(
endpoint: "UrlEndpoint",
equivelanceId: "UniqueID",
httpMethod: .GET,
sessionType: .json,
taskType: .dataTask,
payload: Any,
params: [:],
headers: [:]
)
处理依赖关系
let firstOp = NetworkOperation(endpoint: "http://github.com").resultJSON { json in
print("First operation executed")
}
let secondOp = NetworkOperation(endpoint: "www.test.com")
secondOp.resultSuccess(dependentOnOperations: [firstOperation]) { errorString in
print("Second to be executed")
}
let doneBlock = BlockOperation {
print("Executed when both operations are finished")
}
doneBlock.addDependency(secReq)
NetworkQueue.globalQueue.addOperation(doneBlock)
处理文件夹中的图像缓存
此代码用于处理从提供的端点获取图像。此方法将在FileManager中缓存图像。
NetworkOperation(endpoint: "www.google.com").resultImage(docCacheType: .cache) { imageData in
print(imageData!)
}
// You can clear cache or document images
NetworkOperation.clearCacheImages()
NetworkOperation.clearDocumentImages()
添加认证
- 注意:您当然可以在“headers参数”中添加认证头,但谁喜欢一遍又一遍地重写代码呢?
假设您想为每次API调用添加一个认证头,只需将这些方法转换为子类并重写它们。
- 然后将为您添加认证头,并在收到
401
时为您处理重新认证。
import
class AuthNetworkOperation: NetworkOperation {
// Restore Session logic
override func restoreSession(completion: @escaping (_ success: Bool)->Void) {
NetworkOperation(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 `AuthNetworkOperation` objects
override func getAuthorizationToken() -> String {
return "AuthToken"
}
}
// Then use this class just like you would the `NetworkOperation` class
AuthNetworkOperation(endpoint: "www.google.com").resultSuccess { error in
guard error == nil else { return }
print("success")
}
安装
Cocoa Pods
在您的PodFile
中添加以下示例pod 'NetOperations'
。
use_frameworks!
target 'InsertAppNameHere' do
pod 'NetOperations'
end
Carthage
在您的Cartfile
中指定
github "zsteed/NetOperations" ~> 0.0.4
访问https://github.com/Carthage/Carthage
获取有关如何设置Carthage的更多信息。