English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
iOS10Después del lanzamiento de la versión oficial, en línea se adaptan a varios XCode8y iOS10artículos en todas partes. Pero para iOS10artículos sobre la adaptación de notificaciones push remotas son escasos. Artículos sobre iOS10Las modificaciones para las notificaciones push son muy grandes, se añadió el Framework UserNotifications, hoy hablaremos sobre la situación de adaptación real de mi proyecto.
I. Habilitar el interruptor Push Notifications en Capabilities
en XCode7en el que, la llave no debe estar abierta, las notificaciones push también se pueden usar normalmente, pero en XCode8en el que, la llave debe estar abierta, de lo contrario se generará un error:
Error Domain=NSCocoaErrorDomain Code=3000 "No se encontró el "aps-la cadena de autorización del entorno "environment" " UserInfo={NSLocalizedDescription=No se encontró el "aps-la cadena de autorización del entorno "environment"}
Después de abrir, se generará el archivo entitlements, aquí puedes configurar el APS Environment
II. Registro de notificaciones push
Primero, introduce el Framework UserNotifications,
import <UserNotifications/UserNotifications.h>
iOS10Se modificó el método de registro de notificaciones push, aquí debemos configurar las versiones diferentes. En el método application didFinishLaunchingWithOptions se modificaron las configuraciones de notificaciones push anteriores (sólo implementé iOS8las configuraciones anteriores)
if (IOS_VERSION >= 10.0) { UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; center.delegate = self; [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) { if (!error) { DLog(@"autorización de solicitud exitosa!"); } }]; else { if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) { //IOS8,创建UIUserNotificationSettings,并设置消息的显示类型 UIUserNotificationSettings *notiSettings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound) categories:nil]; [application registerUserNotificationSettings:notiSettings]; } }
三、UNUserNotificationCenterDelegate代理实现
在iOS10处理推送消息需要实现UNUserNotificationCenterDelegate的两个方法:
- (void)userNotificationCenter:(UNUserNotificationCenter *center willPresentNotification:(UNNotification *notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *response withCompletionHandler:(void (^)())completionHandler
以前处理推送时,信息位于userInfo参数中,而新方法表面上似乎没有这个参数,但实际上我们仍然可以获取到userInfo,如下:
/// 当App在前台时调用回调 - (void)userNotificationCenter:(UNUserNotificationCenter *center willPresentNotification:(UNNotification *notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler { NSDictionary *userInfo = notification.request.content.userInfo; [self handleRemoteNotificationForcegroundWithUserInfo:userInfo]; } /// Llamada de App al hacer clic en la notificación en segundo plano - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler { NSDictionary *userInfo = response.notification.request.content.userInfo; [self handleRemoteNotificationBackgroundWithUserInfo:userInfo]; }
Después de completar la configuración de los tres pasos anteriores, para iOS10La configuración básica de notificaciones push ya se ha adaptado. Si desea personalizar el contenido de notificación o implementar otras acciones de notificación, consulte otros artículos. Aquí solo se ha hecho una adaptación para iOS10de adaptación.
Este artículo ha sido organizado en 'Tutorial de notificaciones push de iOS', bienvenidos a aprender y leer.
Esto es todo el contenido de este artículo, espero que sea útil para su aprendizaje y que todos nos apoyen en el tutorial de clamor.
Declaración: El contenido de este artículo se ha obtenido de la red, pertenece al propietario original, el contenido se ha contribuido y subido por los usuarios de Internet de manera autónoma, este sitio no posee los derechos de propiedad, no ha sido editado por humanos y no asume ninguna responsabilidad legal relacionada. Si encuentra contenido sospechoso de infracción de derechos de autor, por favor envíe un correo electrónico a: notice#oldtoolbag.com (al enviar un correo electrónico, reemplace # con @ para denunciar y proporcione evidencia. Una vez verificada, este sitio eliminará inmediatamente el contenido sospechoso de infracción de derechos de autor.)