我不明白为什么完成块不起作用。首先我找到当前位置,然后使用纬度和经度从服务器获取数据。我还尝试使用NSURLSessionDelegate进行后台会话,但也没有获得任何数据。
- (void)widgetPerformUpdateWithCompletionHandler:(void (^)(NCUpdateResult))completionHandler {
// Perform any setup necessary in order to update the view.
[self updateWidget];
self.placeImageView.image = [UIImage imageNamed:@"no-image"];
self.crowdednessLevelImageView.image = [UIImage imageNamed:@"circle-crowd"];
self.placeImageView.layer.cornerRadius = 10;
NSUserDefaults *defaults = [[NSUserDefaults standardUserDefaults] initWithSuiteName:@"group.wherepeeps.mostCrowdedPlace.widgert"];
NSString *coordinateString = [defaults objectForKey:@"CurrentLocationCoordinateString"];
NSDictionary *responseObject = [defaults objectForKey:@"listOfPlacesForWidget"];
NSLog(@"responseObject - %@", responseObject);
if (coordinateString) {
NSString *stringUrl = [NSString stringWithFormat:@"https://sheltered-fjord-29765.herokuapp.com/api/v1/search?location=%@", coordinateString];
NSURLSession *mySession = [self configureMySession];
NSURL *url = [NSURL URLWithString:stringUrl];
[mySession dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSUserDefaults *defaults = [[NSUserDefaults standardUserDefaults] initWithSuiteName:@"group.wherepeeps.mostCrowdedPlace.widgert"];
[defaults setObject:responseObject forKey:@"listOfPlacesForWidget"];
[defaults synchronize];
NSLog(@"responseObject - %@", responseObject);
completionHandler(NCUpdateResultNewData);
}];
} else {
completionHandler(NCUpdateResultNoData);
}
}
- (NSURLSession *)configureMySession {
if (!self.mySession) {
// NSURLSessionConfiguration* config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.mycompany.myapp.backgroundsession"];
NSURLSessionConfiguration* config = [NSURLSessionConfiguration defaultSessionConfiguration];
// To access the shared container you set up, use the sharedContainerIdentifier property on your configuration object.
config.sharedContainerIdentifier = @"com.mycompany.myappgroupidentifier";
self.mySession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
}
return self.mySession;
}
答案 0 :(得分:0)
尝试使用persormSelectorOnMainThread在主线程上调用Nsurlsession请求。