iOS Push Notification code execution on receive

时间秒杀一切 提交于 2019-12-06 10:55:17

问题


I am developing messaging app for iOS.

I keep users' phone numbers to the server but I don't keep contact names on the backend side.

When the user receives push notification from the server, server sends phone number and message content to the user in notification payload. I implemented application:didReceiveRemoteNotification:fetchCompletionHandler method to show local notification. I look up in local database for phoneContactName:phoneNumber pair and show local notification in the format: %phoneContactName%:%messageContent%

However, the hurdle is that I don't now how to execute this code when the app is not running. I tried to implement application:didFinishLaunchingWithOptions and check there for

NSDictionary *userInfo = [launchOptions valueForKey:UIApplicationLaunchOptionsRemoteNotificationKey];

but this code is not invoked.

So to solve the problem I would like to ask you what architectural model should I use. Should I keep contact names on the server side to send notification.alert from the server side with the name of contact (so far my server doesn't know the name of contact phone number) or is there any way to execute code when the app is not running?

P.S. Also, I calculate the badge number on the client side when notification is received. So, the code execution solution will be better if possible.

Thank you


回答1:


I think your architecture is correct. Your issue is down to one of the App states your app is currently in.

If your app is terminated or has never been opened then the above code in application:didFinishLaunchingWithOptions will be exectued, however, if your app is in a background or suspended state then the below method will be called.

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo` 

Therefore you also need to implemented this in the app delegate.

I hope this helps




回答2:


you have to manage condition for app active or inactive like

UIApplicationState state = [application applicationState];
if (state == UIApplicationStateActive) {

    // Below Code Shows Message While Your Application is in Active State



    else { 
//for app recieving notification in background and tap on notification
}


来源:https://stackoverflow.com/questions/28961393/ios-push-notification-code-execution-on-receive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!