我想使用AFNetworking的AFHTTPSessionManager
仅在Wifi可用时对网络服务器实施上传数据操作(例如,后期操作),即使蜂窝网络可用,操作也应排队。我想我需要使用AFNetworkReachabilityManager
。但在AFNetworking的github中,它只显示了如何使用AFHTTPRequestOperationManager
和manager.operationQueue
。
因此,我想询问我是否可以使用AFHTTPSessionManager
及其operationQueue
以下是我对一些代码片段的想法,这样做是否有意义?
AppDelegate.m
@interface AppDelegate ()
@property (strong, nonatomic) NSURLSession *session;
@property (strong, nonatomic) NSMutableURLRequest *request;
@property (strong, nonatomic) AFHTTPSessionManager *manager;
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self config_sessionManager];
[self config_request];
return YES;
}
- (void)config_sessionManager {
NSURL *baseURL = [NSURL URLWithString:TargetURL];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:kSCIdenitifer];
self.manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL sessionConfiguration:config];
//actually, what is this operationQueue? I don't quit understand it
//sometimes, I see `mainQueue` was used,
//e.g `[[NSOperationQueue mainQueue] addOperation:op]` in GET example in the Github
NSOperationQueue *operationQueue = self.manager.operationQueue;
[self.manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusReachableViaWiFi:
[operationQueue setSuspended:NO];
break;
default:
[operationQueue setSuspended:YES];
break;
}
}];
[self.manager.reachabilityManager startMonitoring];
}
- (void)config_request {
self.request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:kTargetURL]];
self.request.HTTPMethod = @"POST";
self.request.HTTPBody = [self.m_str dataUsingEncoding:NSUTF8StringEncoding];
}
- (void)run_task {
NSURLSessionUploadTask * task = [self.manager uploadTaskWithStreamedRequest:self.request progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (!error) {
//ok, no error
NSLog(@"upload data successfully!!!!");
}
else {
//there is error
NSLog(@"error with uploading data!!!!");
}
}];
[task resume];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
[self run_task];
completionHandler(UIBackgroundFetchResultNewData);
}
@end
所以,如果我这样做,如果Wifi不可用,我会在会话管理器中排队任务config_task
吗?如果以后的Wifi再次可用,那么任务是否会恢复并且数据是我想要的?