Monday, 6 March 2017

Map & Button in Push Notification

Map & Button in Push Notification 


**Note :- Map Implementation demo in our Post


*** Preview how Image Show in Notification :







1 ) import Framwork :

 #import <UserNotifications/UserNotifications.h>

2 ) Set delegate :

UNUserNotificationCenterDelegate >


3 ) Coding in didFinishlaunching method in appdelegate :

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {


           // Push Notification
    
    // ****************  Apple Push Integration Starts Here    **************** //
    // ---------------------------------------------------------------------- //
    

    
    /// New iOS 8 User Notification Settings
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    
    if (userInfo != NULL)
    {
        NSString *notification = [[userInfo valueForKey:@"aps"] valueForKey:@"alert"];
    }
    
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000
    
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error){
        if( !error ){
            [[UIApplication sharedApplication] registerForRemoteNotifications];
        }
    }];
    
    
#endif

       // ---------------------------------------------------------------------- //
    
    [application registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                     UIRemoteNotificationTypeAlert |
                                                     UIRemoteNotificationTypeSound)];
    
    [self pushNotificationSetup];
    
    return YES;
}


4 ) Coding in Appdelegate :


-(void)pushNotificationSetup
{
    
    UIMutableUserNotificationAction *notificationAction1 = [[UIMutableUserNotificationAction alloc] init];
    notificationAction1.identifier = @"STOP";
    notificationAction1.title = @"STOP";
    notificationAction1.activationMode = UIUserNotificationActivationModeForeground;
    notificationAction1.destructive = NO;
    notificationAction1.authenticationRequired = YES;
    
    UIMutableUserNotificationAction *notificationAction2 = [[UIMutableUserNotificationAction alloc] init];
    notificationAction2.identifier = @"ROUTE";
    notificationAction2.title = @"ROUTE";
    notificationAction2.activationMode = UIUserNotificationActivationModeForeground;
    notificationAction2.destructive = NO;
    notificationAction2.authenticationRequired = YES;
    
    UIMutableUserNotificationAction *notificationAction3 = [[UIMutableUserNotificationAction alloc] init];
    notificationAction3.identifier = @"Cancel";
    notificationAction3.title = @"Cancel";
    notificationAction3.activationMode = UIUserNotificationActivationModeBackground;
    notificationAction3.destructive = YES;
    notificationAction3.authenticationRequired = YES;
    
    UIMutableUserNotificationCategory *notificationCategory = [[UIMutableUserNotificationCategory alloc] init];
    notificationCategory.identifier = @"pusher";
    [notificationCategory setActions:@[notificationAction1,notificationAction2,notificationAction3] forContext:UIUserNotificationActionContextDefault];
    [notificationCategory setActions:@[notificationAction1,notificationAction2,notificationAction3] forContext:UIUserNotificationActionContextMinimal];
    
    NSSet *categories = [NSSet setWithObjects:notificationCategory, nil];
    
    UIUserNotificationType notificationType = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
    UIUserNotificationSettings *notificationSettings = [UIUserNotificationSettings settingsForTypes:notificationType categories:categories];
    
    [[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings];
}




// ****************  Apple Push Integration Here    **************** //
// ---------------------------------------------------------------------- //


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    UDID = [self tokenStr:deviceToken] ;
    NSLog(@"UDID : %@" , UDID) ;
   
    NSLog(@"tk : %@" , deviceToken) ;
    
}

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
    //[application registerForRemoteNotifications];
    
    if (notificationSettings.types != UIUserNotificationTypeNone) {
        NSLog(@"didRegisterUser");
        [application registerForRemoteNotifications];
    }
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //  NSLog(@"Did Fail to Register for Remote Notifications");
    NSLog(@"%@, %@", error, error.localizedDescription);
   

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%@",error] message:[NSString stringWithFormat:@"%@",error.localizedDescription] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] ;
    
    [alert show] ;
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber + 1;
    
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
}

#pragma mark - DeviceToken

-(NSString *)tokenStr:(NSData *)devicetoken
{
    NSString * deviceTokenString = [[devicetoken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    deviceTokenString = [deviceTokenString stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    NSLog(@"token : %@" , deviceTokenString) ;
    
    return deviceTokenString ;
}


//====================For iOS 10====================

-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
    /*
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"App is in Foreground" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] ;
    
    [alert show] ;*/
    
    //Called when a notification is delivered to a foreground app.

    /*
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef ref = CFBundleCopyResourceURL(mainBundle, (CFStringRef)@"Alarm.wav", NULL, NULL);
    AudioServicesCreateSystemSoundID(ref, &soundID);
    AudioServicesPlaySystemSound(soundID);*/
    
    NSLog(@"Userinfo %@",notification.request.content.userInfo);
    
    completionHandler(UNNotificationPresentationOptionAlert);
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber + 1;
     
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    
}

-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{
    
    /*
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"App is in background" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] ;
    
    [alert show] ;*/
    
    //Called to let your app know which action was selected by the user for a given notification.
    
    NSLog(@"Userinfo %@",response.notification.request.content.userInfo);
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber + 1;
       
    
    if ([response.actionIdentifier isEqualToString:@"STOP"]) {
        NSLog(@"STOP");
    
    }
    else if ([response.actionIdentifier isEqualToString:@"Reject"]) {
        NSLog(@"Reject");
    }
    else if([response.actionIdentifier isEqualToString:@"Reply"])
    {
        NSLog(@"Reply");
    }
    if (completionHandler) {
        completionHandler();
    }    
}


5 ) add New Target :





6 ) Set plist like Below :




7 ) Coding in NotificationViewController :


#import "NotificationViewController.h"
#import <UserNotifications/UserNotifications.h>
#import <UserNotificationsUI/UserNotificationsUI.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>

@interface NotificationViewController () <UNNotificationContentExtension,MKMapViewDelegate,CLLocationManagerDelegate>
{
    NSString *latitude ;
    
    NSString *longitude ;
    
    CGFloat Current_latitude ;
    
    CGFloat Current_longitude ;
}
@property IBOutlet UILabel *label;

@property IBOutlet MKMapView *mapview;

@property(strong,nonatomic)CLLocationManager *locationManager ;


@property (strong, nonatomic) MKPlacemark *destination;
@property (strong,nonatomic) MKPlacemark *source;

@end

@implementation NotificationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    _locationManager = [[CLLocationManager alloc] init];
    _locationManager.delegate=self;
    _locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
    _locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
    
    
    Current_latitude = _locationManager.location.coordinate.latitude ;
    
    Current_latitude = _locationManager.location.coordinate.longitude ;
    
     [self getDirections];
}

- (void)didReceiveNotification:(UNNotification *)notification {
    self.label.text = notification.request.content.body;
       
}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
     CLLocationCoordinate2D sourceCoords = CLLocationCoordinate2DMake(37.773972, -122.431297);
    
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(sourceCoords, 4000, 4000);
    [mapView setRegion:[mapView regionThatFits:region] animated:YES];
    
}

-(void)getDirections {
    
    CLLocationCoordinate2D sourceCoords = CLLocationCoordinate2DMake(37.756972, -122.451297);
    
    MKCoordinateRegion region;
    //Set Zoom level using Span
    MKCoordinateSpan span;
    region.center = sourceCoords;
    
    span.latitudeDelta = 1;
    span.longitudeDelta = 1;
    region.span=span;
    [_mapview setRegion:region animated:TRUE];
    
    MKPlacemark *placemark  = [[MKPlacemark alloc] initWithCoordinate:sourceCoords addressDictionary:nil];
    
    MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
    annotation.coordinate = sourceCoords;
    annotation.title = @"San Francisco";
    [_mapview addAnnotation:annotation];
    //[self.myMapView addAnnotation:placemark];
    
    _destination = placemark;
    
    MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:_destination];
    
    CLLocationCoordinate2D destCoords = CLLocationCoordinate2DMake(37.775223, -122.431977);
    MKPlacemark *placemark1  = [[MKPlacemark alloc] initWithCoordinate:destCoords addressDictionary:nil];
    
    MKPointAnnotation *annotation1 = [[MKPointAnnotation alloc] init];
    annotation1.coordinate = destCoords;
    annotation1.title = @"San Francisco University";
    [_mapview addAnnotation:annotation1];
    
    //[self.myMapView addAnnotation:placemark1];
    
    _source = placemark1;
    
    MKMapItem *mapItem1 = [[MKMapItem alloc] initWithPlacemark:_source];
    
    MKDirectionsRequest *request = [[MKDirectionsRequest alloc] init];
    request.source = mapItem1;
    
    request.destination = mapItem;
    request.requestsAlternateRoutes = NO;
    
    MKDirections *directions = [[MKDirections alloc] initWithRequest:request];
    
    [directions calculateDirectionsWithCompletionHandler:
     ^(MKDirectionsResponse *response, NSError *error) {
         if (error) {
             NSLog(@"ERROR");
             NSLog(@"%@",[error localizedDescription]);
         } else {
             [self showRoute:response];
         }
     }];
}

-(void)showRoute:(MKDirectionsResponse *)response
{
    for (MKRoute *route in response.routes)
    {
        [_mapview
         addOverlay:route.polyline level:MKOverlayLevelAboveRoads];
        
        for (MKRouteStep *step in route.steps)
        {
            NSLog(@"%@", step.instructions);
        }
    }
}

#pragma mark - MKMapViewDelegate methods

- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
    MKPolylineRenderer *renderer = [[MKPolylineRenderer alloc] initWithPolyline:overlay];
    renderer.strokeColor = [UIColor colorWithRed:0.0/255.0 green:171.0/255.0 blue:253.0/255.0 alpha:1.0];
    renderer.lineWidth = 4.0;
    return  renderer;
}

@end








No comments:

Post a Comment