您好,我在应用程序中使用DISPATCH_TIME_FOREVER
进行API调用。当网络速度较慢时,它似乎阻塞了主线程。我对此DISPATCH_TIME_FOREVER
不太了解。谁能指导我。这是我正在使用的代码。
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSMutableDictionary *postDic=[[NSMutableDictionary alloc]init];
[postDic setObject:@"getProfileDetails" forKey:@"cmd"];
[postDic setObject:[[NSUserDefaults standardUserDefaults]objectForKey:@"accountnumber"] forKey:@"accountNumber"];
[postDic setObject:[[NSUserDefaults standardUserDefaults]objectForKey:@"deviceID"] forKey:@"deviceId"];
NSData *postData;
dispatch_group_t group=dispatch_group_create();
if(postDic!=nil)
postData=[NSJSONSerialization dataWithJSONObject:postDic options:0 error:nil];
NSString *postLength=[NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
// remote ip
NSString *remoteAddress=[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"remoteIP"]];
NSURL *url=[NSURL URLWithString:remoteAddress];
NSMutableURLRequest *request =[[NSMutableURLRequest alloc]init];
[request setURL:url];
[request setHTTPMethod:@"Post"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:[NSString stringWithFormat:@"%@ %@",[[NSUserDefaults standardUserDefaults] valueForKey:@"tokenType"],[[NSUserDefaults standardUserDefaults] valueForKey:@"accessToken"]] forHTTPHeaderField:@"Authorization"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setTimeoutInterval:10.0];
[request setHTTPBody:postData];
dispatch_group_enter(group);
NSURLSessionConfiguration *profileConfiguration=[NSURLSessionConfiguration defaultSessionConfiguration];
profileConfiguration.timeoutIntervalForResource=30.0;
profileConfiguration.timeoutIntervalForRequest=30.0;
NSURLSession *profileSession=[NSURLSession sessionWithConfiguration:profileConfiguration];
NSURLSessionDataTask *profileTask=[profileSession dataTaskWithRequest:request
completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
{
NSLog(@"profile Error is %@",error);
NSDictionary* lineUpStationsResponse;
if(data!=nil)
profileResponse=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
// If result is null then send empty dictionary back to viewcontroller to display that login customer not subscribed to any service
if(error!=nil)
{
completionBlock(postDic,nil,error);
}
if([NSJSONSerialization isValidJSONObject:lineUpStationsResponse])
{
completionBlock(postDic,profileResponse,error);
}
else
{
NSDictionary *resultDic=[[NSDictionary alloc]init];
completionBlock(postDic,resultDic,error);
}
// NSLog(@"profile is %@",profileResponse);
dispatch_group_leave(group);
}];
[profileTask resume];
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
});