如何在iOS 10[Objective C]中实现推送通知?

18

有人能帮我实现 iOS 10 的推送通知吗?我已经按照下面的代码实现了,但仍然遇到问题:

#define SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

if(SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(@"10.0"))
{
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error){
        if(!error){
            [[UIApplication sharedApplication] registerForRemoteNotifications];
        }
    }];
}
else {
    // Code for old versions
}

我遇到了错误,提示如下:

未知接收器 UIUserNotificationCenter

提前谢谢!


请查看此链接:https://dev59.com/JFkS5IYBdhLWcg3w25sM#39383027 - Anbu.Karthik
2个回答

50

抱歉,大家,我找到答案了。 我只需要导入UserNotifications框架。

#import <UserNotifications/UserNotifications.h>

5

请查看以下内容

#import <UserNotifications/UserNotifications.h>

然后

    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
        UIUserNotificationType allNotificationTypes =
        (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings =
        [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
        [application 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)
        [UNUserNotificationCenter currentNotificationCenter].delegate = self;
        UNAuthorizationOptions authOptions =
        UNAuthorizationOptionAlert
        | UNAuthorizationOptionSound
        | UNAuthorizationOptionBadge;
        [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
        }];
#endif
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接