ios покажет мне контроллер uialert с полученной информацией об уведомлении - PullRequest
0 голосов
/ 09 мая 2018

Я пишу приложение на objective-c языке. У меня проблема с полученным уведомлением (я использовал сервис oneSignal). когда я отправляю уведомление своему приложению, если состояние приложения активно, то вы видите это (информация, отправленная с уведомлением):

enter image description here

(это тестовое приложение, а не реальное приложение. Извините за этот интерфейс :))

В любом случае, я реализую это приложение с тем же кодом моего другого приложения, которое работает без каких-либо проблем, но в этом приложении я столкнулся с этой проблемой ..

Мне кажется, проблема в сертификате службы push-уведомлений Apple. но если вы думаете, что проблема в другом, пожалуйста, помогите мне ... спасибо.

#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
@import UserNotifications;
#endif
@interface AppDelegate ()<UNUserNotificationCenterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [FIRApp configure];

    [OneSignal initWithLaunchOptions:launchOptions appId:@"fc0695b4-3a0d-4cd3-882d-00ebdba6729f"];



    NSDictionary *remoteNotificationPayload = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (remoteNotificationPayload) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"notification" object:nil userInfo:remoteNotificationPayload];
    }


    [[UIApplication sharedApplication] registerForRemoteNotifications];



    //    // Register for remote notifications. This shows a permission dialog on first run, to
    //    // show the dialog at a more appropriate time move this registration accordingly.
    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
        // iOS 7.1 or earlier. Disable the deprecation warnings.
        NSLog(@"ios 7;");
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        UIRemoteNotificationType allNotificationTypes =
        (UIRemoteNotificationTypeSound |
         UIRemoteNotificationTypeAlert |
         UIRemoteNotificationTypeBadge);
        [application registerForRemoteNotificationTypes:allNotificationTypes];
#pragma clang diagnostic pop
    } else {
        NSLog(@"ios 8");
        // iOS 8 or later
        // [START register_for_notifications]
        if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
            UNAuthorizationOptions allNotificationTypes =
            (UNAuthorizationOptionSound | UNAuthorizationOptionNone | UNAuthorizationOptionBadge);
            UIUserNotificationSettings *settings =
            [UIUserNotificationSettings settingsForTypes:(UIUserNotificationType)allNotificationTypes categories:nil];



            [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        } else {
            // iOS 10 or later
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
            // For iOS 10 display notification (sent via APNS)
            NSLog(@"ios 10");
            [UNUserNotificationCenter currentNotificationCenter].delegate = self;
            UNAuthorizationOptions authOptions =
            UNAuthorizationOptionNone
            | UNAuthorizationOptionSound
            | UNAuthorizationOptionBadge;
            [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
            }];
            [UNUserNotificationCenter currentNotificationCenter].delegate = self;
#endif
        }

        [[UIApplication sharedApplication] registerForRemoteNotifications];
        // [END register_for_notifications]
    }





    return YES;
}


-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification

    // Print full message.
    NSLog(@"didReceiveRemoteNotification %@", userInfo);

    if (application.applicationState == UIApplicationStateActive) {
        // Nothing to do if applicationState is Inactive, the iOS already displayed an alert view.
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Did receive a Remote Notification" message:[NSString stringWithFormat:@"Your App name received this notification while it was running:\n%@",[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]]delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alertView show];
    }
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification

    // Print full message.
    NSLog(@"didReceiveRemoteNotification %@", userInfo);

    completionHandler(UIBackgroundFetchResultNewData);
}
// [END receive_message]

// [START ios_10_message_handling]
// Receive displayed notifications for iOS 10 devices.
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
// Handle incoming notification messages while app is in the foreground.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
#define ROOTVIEW [[[UIApplication sharedApplication] keyWindow] rootViewController]
    // Print message ID.
    NSDictionary *userInfo = notification.request.content.userInfo;
    // Print full message.
    NSLog(@"willPresentNotification %@", userInfo);


    NSDictionary *dic = [userInfo objectForKey:@"aps"];
    NSDictionary *dic2 = [dic objectForKey:@"alert"];

    if ([[dic2 objectForKey:@"title"] isEqualToString:@"new-order"]) {

        NSError *eror = nil;
        NSString *body = [dic2 objectForKey:@"body"];
        NSData *data = [body dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dict3 = [NSJSONSerialization JSONObjectWithData:data options:0 error:&eror];
        NSLog(@"dict3 i s:%@",dict3);
    }else if([[dic2 objectForKey:@"title"] isEqualToString:@"order-canceled"]){



    }





    // Change this to your preferred presentation option
    //    completionHandler(UNNotificationPresentationOptionNone);
}








// Handle notification messages after display notification is tapped by the user.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)(void))completionHandler {
    NSDictionary *userInfo = response.notification.request.content.userInfo;

    // Print full message.
    NSLog(@"didReceiveNotificationResponse %@", userInfo);
    completionHandler();
}
#endif



- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"Unable to register for remote notifications: %@", error);
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
    NSLog(@"gereftam");
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *iosVersion = [NSString stringWithFormat:@"%@",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];

    NSLog(@"APNs token retrieved: %@", deviceToken);
    NSString *str = [@"~/Documents/deviceToken.txt" stringByExpandingTildeInPath];
    NSString *token = [NSString stringWithFormat:@"%@",deviceToken];
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    token = [token stringByReplacingOccurrencesOfString:@">" withString:@""];
    token = [token stringByReplacingOccurrencesOfString:@"<" withString:@""];
    NSLog(@"token is :%@",token);
    NSDictionary *devicetoken = [[NSDictionary alloc] init];
    devicetoken = @{
                    @"token":token,
                    @"iosVersion":iosVersion
                    };


    [devicetoken writeToFile:str atomically:YES];
}
...