如何在iOS应用程序上实现Apple推送通知服务?

如何在iOS应用程序上实现Apple推送通知服务?,ios,xcode,push-notification,apple-push-notifications,Ios,Xcode,Push Notification,Apple Push Notifications,是否有任何示例项目显示如何在IPhone上集成APNS,以及如何使设备正常运行?您需要遵循以下几个简单步骤: 在应用程序代理的didFinishLaunchingWithOptions中,您应该注册远程通知。请注意,苹果的文档建议每次应用程序运行时注册,因为代币可能会不时更改。为此,请拨打: [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert | U

是否有任何示例项目显示如何在
IPhone
上集成
APNS
,以及如何使设备正常运行?

您需要遵循以下几个简单步骤:

  • 在应用程序代理的didFinishLaunchingWithOptions中,您应该注册远程通知。请注意,苹果的文档建议每次应用程序运行时注册,因为代币可能会不时更改。为此,请拨打:

    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound];
    
  • 注册远程通知后,将调用已传递令牌的应用程序代理中的方法,您需要在应用程序代理中实现此方法,并将令牌发送到服务器(该服务器将向您发送通知)。方法如下所示:

    - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    
        NSLog(@"device token is: %@",deviceToken);
        [server sendToken:deviceToken];
    }
    
    5810F4C8C2AF5F7 F7 D6AF71A 22745D0FB50DED 665E0E882 BC5370D9CF0A F19E16  
    
  • 您还应该实现这一点:

        -(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{}
    
  • 您需要在收到通知后处理它们。处理收到的通知的场景很少(应用程序位于后台或前台等),当您接收到通知时,如果应用程序位于前台,则处理通知的方法应在应用程序代理中实现。就是这样:

    -(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
        NSLog(@"received notification");
        //handle the notification here
    }
    
  • 要了解有关userInfo结构的更多信息并涵盖所有不同的场景,请仔细阅读。这只是要点:)

    -(BOOL)应用程序:(UIApplication*)应用程序使用选项完成启动:(NSDictionary*)启动选项{
    //如果在iOS 8上运行,请注册推送通知
    如果([[[UIDevice currentDevice]systemVersion]floatValue]>=8.0){
    [[UIApplication sharedApplication]registerUserNotificationSettings:[UIUserNotificationSettings设置类型:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge)类别:nil];
    [[UIApplication sharedApplication]注册表项的删除];
    }否则{
    [应用程序注册表的通知类型:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
    }
    返回YES;
    }
    #布拉格标记
    #pragma标记--推送通知委托方法
    -(void)应用程序:(UIApplication*)应用程序didRegisterUserNotificationSettings:(UIUserNotificationSettings*)notificationSettings{
    //注册以接收通知
    [申请登记处证明];
    }
    -(无效)应用程序:(UIApplication*)应用程序DIdRegisterForRemotionTificationswithDeviceToken:(NSData*)deviceToken{
    //准备要注册的设备令牌(删除空格和<>)
    NSString*devToken=[[[deviceToken描述]
    StringByReplacingOfString:@“with String:@”]
    StringByReplacingOfString:@“和字符串:@]”发生;
    NSLog(@“我的令牌是:%@”,devToken);
    }
    -(无效)应用程序:(UIApplication*)应用程序未能注册远程通知,错误为:(N错误*)错误{
    //NSLog(@“无法获取令牌,错误:%@”,错误);
    }
    -(无效)应用程序:(UIApplication*)应用程序DidReceiveMemotentification:(NSDictionary*)用户信息{
    NSLog(@“%s..userInfo=%@”,函数,userInfo);
    /**
    *收到push后,根据您的要求将代码转储到此处
    */
    }
    
    以下是一篇关于如何在iOS中启用和发送推送通知的简要文档

    启用推送通知

    设置推送通知的第一步是为应用程序启用Xcode 8中的功能。只需转到目标的项目编辑器,然后单击“功能”选项卡。查找推送通知并将其值切换为“开”:

    切换功能

    Xcode应显示两个复选标记,指示该功能已成功启用。在幕后,Xcode在开发人员中心创建应用程序ID,并为您的应用程序启用推送通知服务

    注册设备

    需要唯一标识设备才能接收推送通知

    APN为安装应用程序的每个设备分配了一个唯一的设备令牌,您可以使用该令牌在任何给定时间推送该设备。一旦为该设备分配了唯一令牌,则应将其保留在后端数据库中

    示例设备令牌如下所示:

    - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    
        NSLog(@"device token is: %@",deviceToken);
        [server sendToken:deviceToken];
    }
    
    5810F4C8C2AF5F7 F7 D6AF71A 22745D0FB50DED 665E0E882 BC5370D9CF0A F19E16  
    
    要为当前设备请求设备令牌,请打开AppDelegate.swift,并在返回语句之前将以下内容添加到didFinishLaunchingWithOptions回调函数中:

    // iOS 10 support
    if #available(iOS 10, *) {  
        UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }
        application.registerForRemoteNotifications()
    }
    // iOS 9 support
    else if #available(iOS 9, *) {  
        UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
        UIApplication.shared.registerForRemoteNotifications()
    }
    // iOS 8 support
    else if #available(iOS 8, *) {  
        UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
        UIApplication.shared.registerForRemoteNotifications()
    }
    // iOS 7 support
    else {  
        application.registerForRemoteNotifications(matching: [.badge, .sound, .alert])
    }
    
    在iOS 10中,引入了一个名为UserNotifications的新框架,必须导入该框架才能访问UNUserNotificationCenter类

    将以下导入语句添加到AppDelegate.swift的顶部:

    import UserNotifications 
    
    接下来,转到目标的项目编辑器,在General选项卡中查找链接的框架和库部分

    单击+并选择UserNotifications.framework:

    接下来,在AppDelegate.swift中添加以下回调,当APNs成功注册或注册设备以接收通知失败时,将调用该回调:

    // Called when APNs has assigned the device a unique token
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {  
        // Convert token to string
        let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
    
        // Print it to console
        print("APNs device token: \(deviceTokenString)")
    
        // Persist it in your backend in case it's new
    }
    
    // Called when APNs failed to register the device for push notifications
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {  
        // Print the error to console (you should alert the user that registration failed)
        print("APNs registration failed: \(error)")
    }
    
    由您来实现将令牌持久化到应用程序后端的逻辑。在本指南的后面部分,您的后端服务器将连接到APN,并通过提供相同的设备令牌来发送推送通知,以指示哪些设备应接收通知

    请注意,由于各种原因,设备令牌将来可能会更改,因此请使用NSUserDefaults(本地键值存储)在本地持久化令牌,并且仅在令牌更改时更新后端,以避免不必要的请求

    对AppDelegate.swift进行必要的修改后,在物理iOS设备上运行应用程序(iOS模拟器无法接收通知)。查找以下对话框,然后按“确定”以允许应用程序接收推送通知:

    // Called when APNs has assigned the device a unique token
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {  
        // Convert token to string
        let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
    
        // Print it to console
        print("APNs device token: \(deviceTokenString)")
    
        // Persist it in your backend in case it's new
    }
    
    // Called when APNs failed to register the device for push notifications
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {  
        // Print the error to console (you should alert the user that registration failed)
        print("APNs registration failed: \(error)")
    }
    
    警报对话框

    在一两秒钟内,Xcode控制台将显示您设备的唯一令牌。复制它并保存以备将来使用

    <