2016-09-27 5 views
1

Я работаю над функцией уведомлений iOS с помощью уведомления push push, прямо сейчас я получаю надлежащее уведомление, когда мое приложение находится в фоновом режиме или на переднем плане, но я хочу обрабатывать удаленное уведомление когда мое приложение находится в фоновом режиме, в основном, когда мое приложение находится в фоновом режиме, оно просто выводит предупреждающее сообщение из полезной нагрузки. Обычно я просто хочу настроить свое удаленное уведомление.Как обращаться с удаленными уведомлениями iOS, когда приложение находится в фоновом режиме

код:

- (BOOL)application:(UIApplication)application didFinishLaunchingWithOptions:(NSDictionary)launchOptions { 
// Override point for customization after application launch. 
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) 
{ 
//  [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]]; 
[[UIApplication sharedApplication] registerForRemoteNotifications]; 
} 
else 
{ 
[[UIApplication sharedApplication] registerForRemoteNotificationTypes: 
(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)]; 
} 
return YES; 
} 
- (void)application:(UIApplication *)application 
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error 
{ 
NSLog(@"Did Register for Remote Notifications with Device Token (%@)", error); 
} 
- (void)application:(UIApplication)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData)deviceToken { 
NSLog(@"Did Register for Remote Notifications with Device Token (%@)", deviceToken); 
} 
-(void)application:(UIApplication)application didReceiveRemoteNotification:(NSDictionary)userInfo fetchCompletionHandler:(void (UIBackgroundFetchResult))completionHandler 
{ 
NSDictionary * aps=[userInfo valueForKey"aps"]; 
NSLog(@"did recevie %@",aps); 
NSLog(@"userinfo details %@",[aps valueForKey"alert"]); 
} 
+0

, какую версию iOS вы используете в своем тестовом устройстве? – Himanth

+0

Для iOS 10 и выше вам нужно сделать что-то еще – Himanth

+0

Это в ios 10.0 –

ответ

2

В прошивке 10 первых вы должны установить UNUserNotificationCenterDelegate в AppDelegate.h файле

@interface AppDelegate : UIResponder <UIApplicationDelegate,CLLocationManagerDelegate,UNUserNotificationCenterDelegate> 

После этого в AppDelegate.m написании кода, как этот

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.1) { 
      // iOS 7.1 or earlier. Disable the deprecation warnings. 
      UIRemoteNotificationType allNotificationTypes = 
      (UIRemoteNotificationTypeSound | 
      UIRemoteNotificationTypeAlert | 
      UIRemoteNotificationTypeBadge); 
      [application registerForRemoteNotificationTypes:allNotificationTypes]; 
      [[UIApplication sharedApplication] registerForRemoteNotifications]; 
     } else { 
      // iOS 8 or later 
      // [START register_for_notifications] 
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0) 
    { 
       UIUserNotificationType allNotificationTypes = 
       (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge); 
       UIUserNotificationSettings *settings = 
       [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil]; 
       [application registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)]; 
       [[UIApplication sharedApplication] registerUserNotificationSettings:settings]; 
       [[UIApplication sharedApplication] registerForRemoteNotifications]; 
       [application registerForRemoteNotifications]; 
      } else { 
       // iOS 10 or later 
    #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 
       UNAuthorizationOptions authOptions = 
       UNAuthorizationOptionAlert 
       | UNAuthorizationOptionSound 
       | UNAuthorizationOptionBadge; 
       [[UNUserNotificationCenter currentNotificationCenter] 
       requestAuthorizationWithOptions:authOptions 
       completionHandler:^(BOOL granted, NSError * _Nullable error) { 
       } 
       ]; 
       // For iOS 10 display notification (sent via APNS) 
       [[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];    
    [[UIApplication sharedApplication] registerForRemoteNotifications]; 
     return YES; 
} 

Теперь это реализовать метод ниже версии iOS10

- (void)application:(UIApplication *)application 
    didReceiveRemoteNotification:(NSDictionary *)userInfo 
    fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))handler { 
     NSLog(@"Notification received: %@", userInfo); 
     if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) 
     { 
      NSLog(@"iOS version >= 10. Let NotificationCenter handle this one."); 
      return; 
     } 
     NSLog(@"HANDLE PUSH, didReceiveRemoteNotification: %@", userInfo); 
      else{ 
      handler(UIBackgroundFetchResultNewData); 
} 

    } 

Apple вводит эти два метода в iOS10 для получения push-уведомлений.

Запишите эти методы также

// Receive displayed notifications for iOS 10 devices. 
    #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 
    - (void)userNotificationCenter:(UNUserNotificationCenter *)center 
      willPresentNotification:(UNNotification *)notification 
      withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler { 

     NSDictionary *userInfo = notification.request.content.userInfo; 

     NSLog(@"%@", userInfo); 

      completionHandler(UNNotificationPresentationOptionAlert); 
    } 

-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{ 

    NSLog(@"Userinfo %@",response.notification.request.content.userInfo); 
// completionHandler(UNNotificationPresentationOptionAlert); 
     } 

Вот и все.

Пробуйте

+1

Ни один из этих методов не выполняется imho, когда приложение backround – luky

+0

Да, ни один из этих методов не называется – kemdo

Смежные вопросы