简体   繁体   中英

Call Web Service when receiving silent push notification?

I have following code:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
  NSLog(@"Silent notification %@", userInfo);
  if([userInfo[@"aps"][@"content-available"] intValue]== 1) //it's the silent notification
  {
    NSLog(@"It is 1!");
    [self callWebService];

    completionHandler(UIBackgroundFetchResultNewData);
    return;
  }
  else
  {
    NSLog(@"It is not 1!");
    completionHandler(UIBackgroundFetchResultNoData);
    return;
  }
}

#pragma mark - Web Service
- (void)callWebService {
  NSLog(@"call web service");
  cdata_branches=[NSMutableData data];

  NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
  [request setURL:[NSURL URLWithString:[NSString stringWithFormat:someURL]]];
  conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
}

#pragma mark -
#pragma mark Connection

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
  [cdata_branches setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
  [cdata_branches appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
  NSString *s_json=[[NSString alloc] initWithData:cdata_branches encoding:NSUTF8StringEncoding];
  NSLog(@"connectionDidFinishLoading JSON data=\n%@",s_json);

  UIAlertView *alertView;
  alertView = [[UIAlertView alloc] initWithTitle:@"Success"
                                         message:[s_json substringWithRange:NSMakeRange (25, 50)]
                                        delegate:nil
                               cancelButtonTitle:@"OK"
                               otherButtonTitles:nil];
  [alertView show];
}

I am able to get the silent PN, however, the call web service seems failed, because it doesn't go to - (void)connectionDidFinishLoading:(NSURLConnection *)connection .

Anyone knows what could be wrong?

Note:

The web service 100% works if called from - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

Enable background fetch in Application background modes.

Enable Remote notifications in Application background modes.

Remote notifications is a special (and rather poorly named) background mode that allows the app to download content in response to a push notification.

You will have 30 seconds to complete your data fetching. Finally call completion handler when the fetching is done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM