我正在使用AFHTTPSessionManager多次从API检索信息。当它不在后台模式下时,它可以正常工作,尽管一旦关闭应用程序,AFHTTPSessionManager调用似乎就无法正常工作,它将阻止。
-(void)requestGET:(NSString *)strURL xml:(BOOL)xml Token:(NSString *)token success:(void (^)(NSDictionary *responseObject))success failure:(void (^)(NSError *error))failure {
BOOL isNetworkAvailable = [self checkNetConnection];
if (!isNetworkAvailable) {
NSLog(@"No connection");
[self showAlert:@"Please check your internet connection"];
return;
}else{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@",token] forHTTPHeaderField:@"Authorization"];
if(xml){
// Content xml
manager.responseSerializer = [AFHTTPResponseSerializer new];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/vnd.garmin.tcx+xml", nil];
}else{
// Content json
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", nil];
}
[manager GET:strURL parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if([responseObject isKindOfClass:[NSDictionary class]]) {
// Return json
if(success) {
success(responseObject);
}
}else{
// Return xml to nsdictionary
if(success){
NSString* responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSDictionary * XMLDictionary = [XMLReader dictionaryForXMLString:responseStr error:nil];
success(XMLDictionary);
}
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"%@", error);
if(failure) {
failure(error);
}
}];
}
}
下面多次调用上述方法,以从API抓取数据并将其抽出。
-(void)getFitbitURL{
// Create group
dispatch_group_t group = dispatch_group_create();
// Retrieve array
NSMutableArray *URLS = [self generateURLS];
for (NSMutableArray *entity in URLS){
NSString *url = entity[0];
// Enter group
dispatch_group_enter(group);
NSString *token = [FitbitAuthHandler getToken];
FitbitAPIManager *manager = [FitbitAPIManager sharedManager];
// Get URL
[manager requestGET:url xml:0 Token:token success:^(NSDictionary *responseObject) {
// Do stuff with output
printf("%s",[[responseObject description]UTF8String]);
// Leave group
dispatch_group_leave(group);
} failure:^(NSError *error) {
NSLog("%@",error);
// Leave group
dispatch_group_leave(group);
}];
}
// Wait for all of group to complete
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"Complete");
});
}
我试图在互联网上研究如何执行此操作,但是我的所有想法都失败了,当应用程序关闭时,我的applicationDidEnterBackground方法可以正常运行,但其他所有功能(例如url请求)均无法正常运行。任何建议,将不胜感激