Ios- How to Integrate Push Notification in iOS 10

iOS- How to integrate push notification in iOS 10?

type converson

Sample Image

for Swift3

Sample Image

-

for sample see this

import the UserNotifications framework and add the UNUserNotificationCenterDelegate in 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, .providesAppNotificationSettings]) { (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]])
token = token + String(format: "%02.2hhx", arguments: [deviceToken[i]])
}

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

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

receive the Notifications using this delegates

 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)")
}

func userNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification?) {
let navController = self.window?.rootViewController as! UINavigationController
let notificationSettingsVC = NotificationSettingsViewController()
navController.pushViewController(notificationSettingsVC, animated: true)
}

for more Information you can see in Apple API Reference


objective C

AppDelegate.h has these lines:

Step-1

//Add Framework in your project "UserNotifications"
#import <UserNotifications/UserNotifications.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate,UNUserNotificationCenterDelegate>

Step-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)

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 | UIUserNotificationTypeprovidesAppNotificationSettings) categories:nil]];
[[UIApplication sharedApplication] registerForRemoteNotifications];

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

return YES;
}

This will fire as a result of calling registerForRemoteNotifications:

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

Then, when a user taps a notification, this fires:

This will fire in iOS 10 when the app is foreground or background, but not closed

 -(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 use

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

Then for iOS 12, these two methods:

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

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
openSettingsForNotification:(UNNotification *)notification{
Open notification settings screen in app
}

Push Notifications not being received on iOS 10, but working on iOS 9 and before

Ok I have figured it out. I now have my original Push Notifications that was working on iOS 9 working on iOS 10 with Xcode 8 and Swift 2.3.

I implemented this by making the following changes to my AppDelegate:

1) On my project settings, under the Capabilities Tab, I scroll down to "Push Notifications" and turn it to "ON". This automatically generates an entitlements file that contains the key "APS Environment" and with value "development".

2) In AppDelegate.swift I make several code changes. I start by importing the UserNotifications framework:

import UserNotifications

Then I have AppDelegate implement the UNUserNotificationCenterDelegate protocol:

class AppDelegate: /*Some other protocols I am extending...*/, UNUserNotificationCenterDelegate {

Then I add the following method:

func registerForPushNotifications(application: UIApplication) {

if #available(iOS 10.0, *){
UNUserNotificationCenter.currentNotificationCenter().delegate = self
UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions([.Badge, .Sound, .Alert], completionHandler: {(granted, error) in
if (granted)
{
UIApplication.sharedApplication().registerForRemoteNotifications()
}
else{
//Do stuff if unsuccessful...
}
})
}

else{ //If user is not on iOS 10 use the old methods we've been using
let notificationSettings = UIUserNotificationSettings(
forTypes: [.Badge, .Sound, .Alert], categories: nil)
application.registerUserNotificationSettings(notificationSettings)

}

}

Then I call this newly created function inside didFinishLaunchingWithOptions:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
...
registerForPushNotifications(application)
...
}

I leave my didRegisterForRemoteNotificationsWithDeviceToken method unchanged:

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
//Implement this. Do something with the token I receive. Send it to my push notification server to register the device or something else I'd like to do with the token.
}

Now I implement two new methods for iOS 10 to handle the receiving of Push Notifications:

@available(iOS 10.0, *)
func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {
//Handle the notification
}

@available(iOS 10.0, *)
func userNotificationCenter(center: UNUserNotificationCenter, didReceiveNotificationResponse response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void) {
//Handle the notification
}

I did not remove any of the methods I have previously implemented for Push Notifications in iOS 9.

Push Notification is not working on iOS 10

Need some changes for iOS 10 with xCode 8 GM You need to implement UserNotification.framework and their delegate methods to get work of push notifications and in capabilities needs to enable Push Notifications.

You have to import new UserNotification.framework. Please follow this link : Push notification issue with iOS 10

Updating a delivered notifications ios 10

Each time you create an updated notification...just use the same identifier. For more see this moment for the WWDC video.

The above answer is for local notifications but you're looking for remote notifications...

Still see the same moment to get the idea...the only difference is that for local notifications you have identifier...for remote notifications you have apns-collapse-id header:

Sample Image

So just give a value to apns-collapse-id and each time you send a new one it will update the previous one. Obviously if the user is in the app then you're out of luck, because they've already received the notification. This would only work if the user hasn't opened the notification yet (nor is in the app). If they have opened it then a new notification is sent.

apns-collapse-id

Multiple notifications with the same collapse identifier are displayed
to the user as a single notification. The value of this key must not
exceed 64 bytes. For more information, see Quality of Service,
Store-and-Forward, and Coalesced Notifications.

From Apple docs:

To allow the coalescing* of similar notifications, you can include a
collapse identifier within a notification request. Normally, when a
device is online, each notification request that you send to APNs
results in a notification delivered to the device. However, when the
apns-collapse-id key is present in your HTTP/2 request header, APNs
coalesces requests whose value for that key is the same. For example,
a news service that sends the same headline twice could use the same
collapse identifier value for both requests. APNs would then coalesce
the two requests into a single notification for delivery to the
device. For details on the apns-collapse-id key.


*: come together and form one mass whole

ios10, Swift 3 and Firebase Push Notifications (FCM)

Inside method didRegisterForRemoteNotificationsWithDeviceToken, add the following code:

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
var tokenString = ""

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

FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Unknown)

print("tokenString: \(tokenString)")
}

And do not forget to enable Push Notifications inside Capabilities.

iOS 10 Rich Media Push Notification (Media Attachment) in Objective-C

your code is ok, it just expects a different push notification data format:

Try replacing this part:

// Create the payload body
$body['aps'] = array(
'alert' => $message,
'sound' => 'default',
'mutable-content' => 1,
'category'=> "pusher"
);
$body['data'] = array(
'mediaUrl' => "http://www.alphansotech.com/wp-content/uploads/2015/12/Push-notification-1.jpg",
'mediaType' => "jpg"
);

with:

$body = array(
'aps' => array(
'alert' => 'Rich notification',
'sound' => 'default',
'mutable-content' => 1
),
'mediaUrl' => 'https://upload.wikimedia.org/wikipedia/commons/thumb/2/2a/FloorGoban.JPG/1024px-FloorGoban.JPG',
'mediaType' => 'image'
);

Please note, that image should be accessible via https://



Related Topics



Leave a reply



Submit