SGHTTPRequest
一个轻量级的 AFNetworking 包装器,用于简洁的 HTTP 请求与成功、失败和重试回调块。当失败的请求的网络资源再次可用时,将调用重试块。
CocoaPods 设置
pod 'SGHTTPRequest'
示例 GET 请求
Objective-C
NSURL *url = [NSURL URLWithString:@"http://example.com/things"];
// create a GET request
SGHTTPRequest *req = [SGHTTPRequest requestWithURL:url];
// start the request in the background
[req start];
Swift
let url = NSURL(string: "http://example.com/things")
// create a GET request
let req = SGHTTPRequest(URL: url)
// start the request in the background
req.start()
示例POST请求
Objective-C
NSURL *url = [NSURL URLWithString:@"http://example.com/things"];
// create a POST request
SGHTTPRequest *req = [SGHTTPRequest postRequestWithURL:url];
// set the POST fields
req.parameters = @{@"field": @"value"};
// start the request in the background
[req start];
Swift
let url = NSURL(string: "http://example.com/things")
// create a GET request
let req = SGHTTPRequest.postRequestWithURL(url)
// set the POST fields
req.parameters = ["field": "value"]
// start the request in the background
req.start()
示例:带成功和失败处理器的示例
如果请求成功,将调用可选的 onSuccess
块。如果请求因任何原因失败,则调用可选的 onFailure
块。
Objective-C
NSURL *url = [NSURL URLWithString:@"http://example.com/things"];
// create a GET request
SGHTTPRequest *req = [SGHTTPRequest requestWithURL:url];
// optional success handler
req.onSuccess = ^(SGHTTPRequest *_req) {
NSLog(@"response:%@", _req.responseString);
};
// optional failure handler
req.onFailure = ^(SGHTTPRequest *_req) {
NSLog(@"error:%@", _req.error);
NSLog(@"status code:%d", _req.statusCode);
};
// start the request in the background
[req start];
Swift
let url = NSURL(string: "http://example.com/things")
// create a GET request
let req = SGHTTPRequest(URL: url)
// optional success handler
req.onSuccess = {(request) in
NSLog("response: %@", request.responseString())
}
// optional failure handler
req.onFailure = {(request) in
NSLog("error: %@", request.error())
NSLog("status code: %d", request.statusCode())
}
// start the request in the background
req.start()
带有重试处理示例
如果请求失败,然后在稍后通过网络资源重新可达,将调用可选的 onNetworkReachable
块。
此功能可用于在不可靠的连接上静默重试,从而消除手动“重试”按钮的需求。例如,尝试获取图像可能因无线信号差而失败,但一旦信号改善,图像获取可以完成,而无需用户干预。
实现此功能的最简单方法是,将您的请求数据包含在方法中,并在 onNetworkReachable
块中回调用该方法,从而触发一个新的相同的请求。
Objective-C
- (void)requestThings {
NSURL *url = [NSURL URLWithString:@"http://example.com/things"];
// create a GET request
SGHTTPRequest *req = [SGHTTPRequest requestWithURL:url];
__weak typeof(self) me = self;
// option retry handler
req.onNetworkReachable = ^{
[me requestThings];
};
// start the request in the background
[req start];
}
Swift
func requestThings() {
let url = NSURL(string: "http://example.com/things")
// create a GET request
let req = SGHTTPRequest(URL: url)
// optional success handler
req.onNetworkReachable = { [weak self] in
if let strongSelf = self {
strongSelf.requestThings()
}
}
// start the request in the background
req.start()
}
响应缓存
如果您的服务器使用 ETag 头,则可以本地缓存响应以避免在数据自上次请求以来未更改时产生昂贵的网络流量。将以下代码添加到您的 AppDelegate 的 didFinishLaunchingWithOptions
方法中
Objective-C
[SGHTTPRequest setAllowCacheToDisk:YES]; // allow responses cached by ETag to persist between app sessions
[SGHTTPRequest setMaxDiskCacheSize:30]; // maximum size of the local response cache in MB
Swift
SGHTTPRequest.setAllowCacheToDisk(true) // allow responses cached by ETag to persist between app sessions
SGHTTPRequest.setMaxDiskCacheSize(30) // maximum size of the local response cache in MB
如果HTTP响应已经被缓存到磁盘上,您也可以访问缓存的副本,以便可以进行离线或即时查看数据。
Objective-C
NSURL *url = [NSURL URLWithString:@"http://example.com/things"];
// create a GET request
SGHTTPRequest *req = [SGHTTPRequest requestWithURL:url];
// read the cached response
NSDictionary *responseDict = req.cachedResponseJSON;
if (responseDict[@"my_data_key"]) {
// If available you can update your UI
// immediately with the cached data
}
// optional success handler
req.onSuccess = ^(SGHTTPRequest *_req) {
// You might want to update your UI with
// the fresh response data here
};
// start the request in the background
[req start];
Swift
let url = NSURL(string: "http://example.com/things")
// create a GET request
let req = SGHTTPRequest(URL: url)
// read the cached response
if let responseDict = req.cachedResponseJSON(), responseValue = responseDict["my_data_key"] {
// If available you can update your UI
// immediately with the cached data
}
// optional success handler
req.onSuccess = {(request) in
// You might want to update your UI with
// the fresh response data here
}
// start the request in the background
req.start()
NSNull 处理
如果您不希望响应中包含 NSNull 对象(它们在尝试使用时可能会崩溃,而调用 nil 的方法则安全且为定义好的行为),那么您可以在 AppDelegate 中加入以下代码,以确保从响应中清除它们:
Objective-C
[SGHTTPRequest setAllowNSNull:NO];
Swift
SGHTTPRequest.setAllowNSNull(false)
其他选项
更多信息请参阅 SGHTTPRequest.h
。