0

I am beginner write about IOS push with swift. It works when app is running in foreground but not work while app in background or close. By the way, I can receive alert message by APNS.newPayload().alertBody when app is in background or close. Thank u much for help.

Below is my server and ios code.

iOScode

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {

    print("Recived: \(userInfo)")
    var receiveMsg = userInfo["key1"] as! String
    print("receiveMsg = \(receiveMsg)")

} 

Server Code

    ApnsService service =
    APNS.newService()
    .withCert("ooxx.p12","")
    .withSandboxDestination()
    .build();   


    String payload = APNS.newPayload().customField("key1", "M;senderGCMID5;senderUserID5;userName5;userMessage5").build();
        String token = "token";
        service.push(token, payload);

I have read some question about this topic, but I can not solve this problem.

I have tried the other function in iOS code like below, and it doesn't work.

APNS push working in foreground but not background

I don't know how to implement. Can u teach me ? thanks much

   func application
 (application: UIApplication,          didReceiveRemoteNotification userInfo: [NSObject : AnyObject],    fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) ->   Void) {
    var receiveMsg = userInfo["key1"] as! String
   print("receiveMsg = \(receiveMsg)")

}

thank pralthom for helping, I sovle the problem by setting content value = 1.

reference APN background refresh, setting up AppDelegate.m

Community
  • 1
  • 1
beehuang
  • 339
  • 2
  • 18

1 Answers1

0

I implemented the push notifications in Objective-C. I don't have the code in swift, but I guess it's very similar...

You have to register for push notification in the AppDelegate. Add the following code in the didFinishLaunchingWithOptions delegate:

// Register for Push Notitications, if running iOS 8
if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
            UIUserNotificationType userNotificationTypes = (UIUserNotificationTypeAlert |
                                                            UIUserNotificationTypeBadge |
                                                            UIUserNotificationTypeSound);
            UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:userNotificationTypes
                                                                                     categories:nil];
            [application registerUserNotificationSettings:settings];
            [application registerForRemoteNotifications];
        } else {
            // Register for Push Notifications before iOS 8
            [application registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                             UIRemoteNotificationTypeAlert |
                                                             UIRemoteNotificationTypeSound)];
        }

Then you have to add the following delegates also in the AppDelegate

-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"DEBUG" message:[NSString stringWithFormat:@"Are you sure to use the right provisionning ? %@", error.localizedDescription] delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
        [alert show];
    }

- (void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    //Do whatever you want with the push received

It works in background and also when the app is killed. The app status is different for the OS if the app is killed.

There is one more delegate to add: didRegisterForRemoteNotificationsWithDevicetoken. After you call the registerForRemoteNotifications method of the UIApplication object, the app calls this method when device registration completes successfully. In your implementation of this method, connect with your push notification server and give the token to it. APNs pushes notifications only to the device represented by the token.

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *formattedToken = [[[deviceToken description]
                                 stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]]
                                stringByReplacingOccurrencesOfString:@" "
                                withString:@""];
    [[NSUserDefaults standardUserDefaults] setObject:formattedToken forKey:@"DEVICE_IDENTIFIER"];
    [[NSUserDefaults standardUserDefaults] synchronize];
// Send the device identifier to your server

I think you didn't register the device and that's the reason the push comes only when the app is in foreground.

When you test your push notification, you should reset the push notification settings of your iPhone. You can find how to do this in the following post: Reset push notification settings for app

Community
  • 1
  • 1
Thomas
  • 677
  • 6
  • 10
  • Thank u . I have registered for push notification in the AppDelegate. I can receive message in foreground. My problem is that I can not receive in background. – beehuang Oct 29 '15 at 15:21
  • Can u receive message in background or close when using above code? – beehuang Oct 29 '15 at 15:22
  • I have call didRegisterForRemoteNotificationsWithDeviceToken and get device token. So Server can send to device with token in foreground. – beehuang Oct 30 '15 at 13:27
  • thank u for helping, I sovle the problem by setting content value = 1. http://stackoverflow.com/questions/30104529/apn-background-refresh-setting-up-appdelegate-m – beehuang Oct 31 '15 at 08:40