2016-10-13 48 views

回答

1

如果我們使用IOS 10,我們需要增加新的工作框架和一些代碼

第1步:

從iOS 10開始,我們必須添加UserNotifications框架和委託。首先添加這個。

第2步:

添加委託UNUserNotificationCenterDelegate

現在appDelegate.h

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

appDeleg ate.m

STEP: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; 
} 

STEP:4

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken 
    { 
     // custom stuff we do to register the device with our AWS middleman 
     NSString *strToken = [[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"<>"]]; 
     strToken = [strToken stringByReplacingOccurrencesOfString:@" " withString:@""]; 
     NSLog(@"content---%@", strToken); 

     NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",@"your url here"]]]; 


     [request setHTTPMethod:@"POST"]; 

     //Pass The String to server 
     NSString *userUpdate =[NSString stringWithFormat:@"device_token=%@",strToken,nil]; 

     //Check The Value what we passed 
     NSLog(@"the data Details is =%@", userUpdate); 

     //Convert the String to Data 
     NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding]; 

     //Apply the data to the body 
     [request setHTTPBody:data1]; 

     //Create the response and Error 
     NSURLSession *session = [NSURLSession sharedSession]; 
     NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
     NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; 
     if(httpResponse.statusCode == 200) 
     { 
     if(httpResponse.statusCode == 200) 
     { 
      NSError *parseError = nil; 
      NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError]; 
      NSLog(@"The response is - %@",responseDictionary); 
     } 
     else 
     { 
      NSLog(@"Error"); 
     } 
     } 
     else 
     { 
      NSLog(@"faield to connect"); 
     } 
     }]; 
     [dataTask resume];  

} 

STEP:5

-(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); 
    } 
    } 

//OR 

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo 
{ 
    [self application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:^(UIBackgroundFetchResult result) { 
     }]; 
     NSLog(@"Received notification: %@", userInfo); 
     if ([userInfo count]!=0) 
     { 
     NSMutableArray *notify=[[NSMutableArray alloc]init]; 
     NSMutableArray *mutableRetrievedDictionary; 
    mutableRetrievedDictionary = [[NSUserDefaults standardUserDefaults] objectForKey:@"noyificationcount"] ; 
     NSMutableArray *deviealert = [[NSUserDefaults standardUserDefaults] objectForKey:@"noyificationcount"] ; 
     deviealert=[[NSMutableArray alloc]init]; 
     [notify addObject: [[userInfo valueForKey:@"aps"] valueForKey:@"alert"]]; 
     NSLog(@"notification is - %@", notify); 
     NSString *strAlertValue = [[userInfo valueForKey:@"aps"] valueForKey:@"badge"]; 
     NSLog(@"my message-- %@",strAlertValue); 
     deviealert=[notify mutableCopy]; 
     NSLog(@"new...%@",deviealert); 
     [[ NSUserDefaults standardUserDefaults]setObject:deviealert forKey:@"noyificationcount" ]; 
     [[NSUserDefaults standardUserDefaults]synchronize]; 
     NSLog(@"dev.....%@",deviealert); 
     [UIApplication sharedApplication].applicationIconBadgeNumber+=1; 
     } 


    } 

STEP:6

對於前臺狀態

- (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); 
    } 

STEP:7

對於背景國家

- (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); 

     //Adding notification here 
     [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTheTable" object:nil]; 
    } 
+0

我有JSON API,在那裏我調用API –

+0

請你能張貼代碼。我面臨着很多問題。 –

+0

只需在didRecieveRemoteNotifications中調用json代碼,然後自動發出pushnotifications或使用數組或字符串的結果就是任何東西。 –

2

你可以從下面的鏈接瞭解如何在iOS 10中實現推送通知。在這裏,你還可以找到步驟來實現相同的XCode中8,請參考以下鏈接:Push notification issue with iOS 10

+0

,其中JSON API實現 –