Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
866 views
in Technique[技术] by (71.8m points)

ios - Background task when apns received

After reading APNS documentation, I have implemented apns into my app. Everything works fine, but I have a question. I don't know if it is possible, but I would like to do a task when my app is in background and I receive a apns notification.

This is my dictionary inside the notification:

aps =
{
  alert = "message";
  sound = "default";
};

If my app is in foreground, I execute this code:

- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo
{     
    [HTTPConnection sendGetToUrl:[NSURL URLWithString:stringUrl]];

    NSLog(@"Received notification: %@", userInfo);  
}

But apns does not execute "didReceiveRemoteNotification" when the app is in background, so I would like to execute the method:

[HTTPConnection sendGetToUrl:[NSURL URLWithString:stringUrl]];

if I receive an apns notification in background.

Is there any way to do it?

Thanks so much!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes this is posible since iOS 7, you will need to add remote-notification to the UIBackgroundModes in your apps info.plist .

Then implement the application:didReceiveRemoteNotification:fetchCompletionHandler: in your app delegate. You will have 30 seconds to fetch data, if you app takes longer the system might terminate your.

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler {
   NSString *stringURl = /* some URL */;
   [HTTPConnection sendGetToUrl:[NSURL URLWithString:stringUrl]];

   // Once done call handler with one of the result types:
   // UIBackgroundFetchResultNewData, UIBackgroundFetchResultNoData, UIBackgroundFetchResultFailed

   handler(UIBackgroundFetchResultNewData);
}

You will have to notify the system when the call is done and that data is fetched by call the handler. As stated by the documentation you will need to tell the handler if you succeeded to fetch any data:

handler

The block to execute when the download operation is complete. When calling this block, pass in the fetch result value that best describes the results of your download operation. You must call this handler and should do so as soon as possible. For a list of possible values, see the UIBackgroundFetchResult type.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...