使用Api推送通知

时间:2016-10-13 13:23:42

标签: ios objective-c push-notification

我正在处理推送通知,我有推送通知的api,但我不知道如何实现代码。我正在使用ios 10版本,请帮帮我。

2 个答案:

答案 0 :(得分:2)

您可以通过以下链接全面了解在iOS 10中实施推送通知。在这里,您还可以找到在XCode 8中实现相同步骤的步骤。请参阅以下链接:Push notification issue with iOS 10

答案 1 :(得分:1)

如果我们使用IOS 10,我们需要添加新的框架工作和一些代码

STEP:1

  

从iOS 10开始,我们必须添加UserNotifications框架和delegat.First添加此内容。

STEP:2

  

添加委托UNUserNotificationCenterDelegate

现在 appDelegate.h

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

<强> appDelegate.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];
    }