5

Tôi đã sử dụng mã sau đây dành cho iOS 8,9 như:iOS- Cách tích hợp thông báo đẩy trong iOS 10?

UIMutableUserNotificationAction *action1; 
    action1 = [[UIMutableUserNotificationAction alloc] init]; 
    [action1 setActivationMode:UIUserNotificationActivationModeBackground]; 
    [action1 setTitle:@"REJECT"]; 
    [action1 setIdentifier:NotificationActionOneIdent]; 
    [action1 setDestructive:NO]; 
    [action1 setAuthenticationRequired:NO]; 

    UIMutableUserNotificationAction *action2; 
    action2 = [[UIMutableUserNotificationAction alloc] init]; 
    [action2 setActivationMode:UIUserNotificationActivationModeBackground];////UIUserNotificationActivationModeBackground 
    [action2 setTitle:@"ACCEPT"]; 
    [action2 setIdentifier:NotificationActionTwoIdent]; 
    [action2 setDestructive:NO]; 
    [action2 setAuthenticationRequired:NO]; 

    UIMutableUserNotificationCategory *actionCategory; 
    actionCategory = [[UIMutableUserNotificationCategory alloc] init]; 
    [actionCategory setIdentifier:NotificationCategoryIdent]; 
    [actionCategory setActions:@[action1, action2] 
        forContext:UIUserNotificationActionContextDefault]; 

    NSSet *categories = [NSSet setWithObject:actionCategory]; 

    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes: 
             UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:categories]; 
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings]; 

Xử lý bằng phương pháp đại biểu:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler 
{ 
//Handle according to app state 
} 

Và // Xử lý các hành động

- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler { 
//Handle action as well 
} 

Làm thế nào để làm tương tự trong iOS 10 bằng cách sử dụng khung UserNotifications và UserNotificationsUI? tôi có cần hỗ trợ iOS 8 và iOS 9 không?

Trả lời

36

không quên bật này

enter image description here

cho Swift3 cho mẫu thấy this

nhập khuôn khổ UserNotifications và thêm UNUserNotificationCenterDelegate trong appdelegate

import UserNotifications 

@UIApplicationMain 
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate 


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 
    // Override point for customization after application launch. 

    //create the notificationCenter 
    let center = UNUserNotificationCenter.current() 
    center.delegate = self 
    // set the type as sound or badge 
    center.requestAuthorization(options: [.sound,.alert,.badge]) { (granted, error) in 
     // Enable or disable features based on authorization 

     } 
     application.registerForRemoteNotifications() 
    return true 
} 

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { 
    let chars = UnsafePointer<CChar>((deviceToken as NSData).bytes) 
    var token = "" 

    for i in 0..<deviceToken.count { 
token += String(format: "%02.2hhx", arguments: [chars[i]]) 
    } 

    print("Registration succeeded!") 
    print("Token: ", token) 
} 

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) { 
    print("Registration failed!") 
} 

nhận được thông báo sử dụng các đại biểu này

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (_ options: UNNotificationPresentationOptions) -> Void) { 
    print("Handle push from foreground") 
    // custom code to handle push while app is in the foreground 
    print("\(notification.request.content.userInfo)") 
} 

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping() -> Void) { 
    print("Handle push from background or closed") 
    // if you set a member variable in didReceiveRemoteNotification, you will know if this is from closed or background 
    print("\(response.notification.request.content.userInfo)") 
} 

Thông tin khác bạn có thể thấy trong Apple API Reference

Objective-C

AppDelegate.h đã những dòng:

Bước-1

#import <UserNotifications/UserNotifications.h> 
@interface AppDelegate : UIResponder <UIApplicationDelegate,UNUserNotificationCenterDelegate> 

Bước-2

appdelegate.m

// define macro 
    #define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending) 
    #define SYSTEM_VERSION_LESS_THAN(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending) 

Bước-3

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 
application.applicationIconBadgeNumber = 0; 
    if(SYSTEM_VERSION_LESS_THAN(@"10.0")) 
{ 
    [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]]; 
    [[UIApplication sharedApplication] registerForRemoteNotifications]; 

} 
else 
{ 
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; 
    center.delegate = self; 
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) 
    { 
if(!error) 
    { 
    [[UIApplication sharedApplication] registerForRemoteNotifications]; // required to get the app to do anything at all about push notifications 
    NSLog(@"Push registration success."); 
} 
else 
{ 
    NSLog(@"Push registration FAILED"); 
    NSLog(@"ERROR: %@ - %@", error.localizedFailureReason, error.localizedDescription); 
    NSLog(@"SUGGESTIONS: %@ - %@", error.localizedRecoveryOptions, error.localizedRecoverySuggestion); 
    } 
    }]; 
} 

return YES; 
} 

này sẽ cháy như là kết quả của registerForRemoteNotifications gọi:

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken 
{ 
// custom stuff we do to register the device with our AWS middleman 
} 

Sau đó, khi người dùng chạm một thông báo, thi s cháy:

này sẽ cháy trong iOS 10 khi ứng dụng foreground hoặc background, nhưng không đóng cửa

-(void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void 
    (^)(UIBackgroundFetchResult))completionHandler 
    { 
// iOS 10 will handle notifications through other methods 

if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) 
{ 
    NSLog(@"iOS version >= 10. Let NotificationCenter handle this one."); 
// set a member variable to tell the new delegate that this is background 
    return; 
} 
NSLog(@"HANDLE PUSH, didReceiveRemoteNotification: %@", userInfo); 

// custom code to handle notification content 

if([UIApplication sharedApplication].applicationState == UIApplicationStateInactive) 
{ 
    NSLog(@"INACTIVE"); 
    completionHandler(UIBackgroundFetchResultNewData); 
} 
else if([UIApplication sharedApplication].applicationState == UIApplicationStateBackground) 
{ 
    NSLog(@"BACKGROUND"); 
    completionHandler(UIBackgroundFetchResultNewData); 
} 
else 
{ 
    NSLog(@"FOREGROUND"); 
    completionHandler(UIBackgroundFetchResultNewData); 
} 
} 


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo 
{ 
[self application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:^(UIBackgroundFetchResult result) { 
}]; 
} 

Sau đó, dành cho iOS 10, hai phương pháp:

- (void)userNotificationCenter:(UNUserNotificationCenter *)center 
    willPresentNotification:(UNNotification *)notification 
    withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler 
    { 
    NSLog(@"Handle push from foreground"); 
    // custom code to handle push while app is in the foreground 
    NSLog(@"%@", notification.request.content.userInfo); 
    } 

- (void)userNotificationCenter:(UNUserNotificationCenter *)center 
didReceiveNotificationResponse:(UNNotificationResponse *)response 
    withCompletionHandler:(void (^)())completionHandler 
    { 
    NSLog(@"Handle push from background or closed"); 
    // if you set a member variable in didReceiveRemoteNotification, you will know if this is from closed or background 
    NSLog(@"%@", response.notification.request.content.userInfo); 
    } 
+0

kiểm tra câu trả lời được cập nhật –

+0

Đối với người dùng đã nâng cấp dự án của họ lên XCode 8, hãy đảm bảo bao gồm UserNotifications.framework trong thư viện được liên kết của bạn. –

+0

@SofieVos - chắc chắn –

1

1st) Thêm UserNotifications.framework vào Đã liên kếtFramew orksLibraries trong Cài đặt chung của dự án của bạn

2) Thêm những dòng này để AppDelagte bạn như thế này

#import <UserNotifications/UserNotifications.h> 
@interface AppDelegate() <UIApplicationDelegate,UNUserNotificationCenterDelegate> 

thứ 3) để nhận phản ứng

- (void)userNotificationCenter:(UNUserNotificationCenter *)center 
willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{ 
NSLog(@"for handling push in foreground"); 
// Your code 
NSLog(@"%@", notification.request.content.userInfo); //for getting response payload data 
} 

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler { 
NSLog(@"for handling push in background"); 
// Your code 
NSLog(@"%@", response.notification.request.content.userInfo); //for getting response payload data 
} 
+0

Không có thông số đầu tiên trong "notification.request.content.userInfo" –

+0

Trước tiên, hãy thử in thông báo, tôi nghĩ điều đó sẽ giúp bạn. –

+0

Nó phải là như: response.notification.request.content.userInfo –

Các vấn đề liên quan