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








Get IP & Port

Get IP & Port



**For Port :-


- (int) getPort {
    CFSocketContext socketCtxt = {0, (__bridge void *)(self), NULL, NULL, NULL};
    
    // Start by trying to do everything with IPv6.  This will work for both IPv4 and IPv6 clients
    // via the miracle of mapped IPv4 addresses.
    
    CFSocketRef witap_socket = CFSocketCreate(kCFAllocatorDefault, PF_INET6, SOCK_STREAM, IPPROTO_TCP, kCFSocketAcceptCallBack, nil, &socketCtxt);
    uint32_t protocolFamily;
    
    if (witap_socket != NULL)   // the socket was created successfully
    {
        protocolFamily = PF_INET6;
    } else // there was an error creating the IPv6 socket - could be running under iOS 3.x
    {
        witap_socket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP, kCFSocketAcceptCallBack, nil, &socketCtxt);
        if (witap_socket != NULL)
        {
            protocolFamily = PF_INET;
        }
    }
    
    /*if (NULL == witap_socket) {
     if (error) *error = [[NSError alloc] initWithDomain:TCPServerErrorDomain code:kTCPServerNoSocketsAvailable userInfo:nil];
     if (witap_socket) CFRelease(witap_socket);
     witap_socket = NULL;
     return NO;
     }*/
    
    
    int yes = 1;
    setsockopt(CFSocketGetNative(witap_socket), SOL_SOCKET, SO_REUSEADDR, (void *)&yes, sizeof(yes));
    
    // set up the IP endpoint; use port 0, so the kernel will choose an arbitrary port for us, which will be advertised using Bonjour
    if (protocolFamily == PF_INET6)
    {
        struct sockaddr_in6 addr6;
        memset(&addr6, 0, sizeof(addr6));
        addr6.sin6_len = sizeof(addr6);
        addr6.sin6_family = AF_INET6;
        addr6.sin6_port = 0;
        addr6.sin6_flowinfo = 0;
        addr6.sin6_addr = in6addr_any;
        NSData *address6 = [NSData dataWithBytes:&addr6 length:sizeof(addr6)];
        
        CFSocketSetAddress(witap_socket, (CFDataRef)address6);
        /*if (kCFSocketSuccess != CFSocketSetAddress(witap_socket, (CFDataRef)address6)) {
         if (error) *error = [[NSError alloc] initWithDomain:TCPServerErrorDomain code:kTCPServerCouldNotBindToIPv6Address userInfo:nil];
         if (witap_socket) CFRelease(witap_socket);
         witap_socket = NULL;
         return NO;
         }*/
        
        // now that the binding was successful, we get the port number
        // -- we will need it for the NSNetService
        NSData *addr = (NSData *)CFBridgingRelease(CFSocketCopyAddress(witap_socket));
        memcpy(&addr6, [addr bytes], [addr length]);
        return ntohs(addr6.sin6_port);
        
    } else {
        struct sockaddr_in addr4;
        memset(&addr4, 0, sizeof(addr4));
        addr4.sin_len = sizeof(addr4);
        addr4.sin_family = AF_INET;
        addr4.sin_port = 0;
        addr4.sin_addr.s_addr = htonl(INADDR_ANY);
        NSData *address4 = [NSData dataWithBytes:&addr4 length:sizeof(addr4)];
        
        CFSocketSetAddress(witap_socket, (CFDataRef)address4);
        /*if (kCFSocketSuccess != CFSocketSetAddress(witap_socket, (CFDataRef)address4)) {
         if (error) *error = [[NSError alloc] initWithDomain:TCPServerErrorDomain code:kTCPServerCouldNotBindToIPv4Address userInfo:nil];
         if (witap_socket) CFRelease(witap_socket);
         witap_socket = NULL;
         return NO;
         }*/
        
        // now that the binding was successful, we get the port number 
        // -- we will need it for the NSNetService
        NSData *addr = (NSData *)CFBridgingRelease(CFSocketCopyAddress(witap_socket));
        memcpy(&addr4, [addr bytes], [addr length]);
        return ntohs(addr4.sin_port);
    }
    
}



**For Internal IP :-



- (NSString *)getIPAddress {
    
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                    
                }
                
            }
            
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;
    
}



**For External IP :-



-(NSString*)getIP
{
    NSUInteger  an_Integer;
    NSArray * ipItemsArray;
    NSString *externalIP;
    
    NSURL *iPURL = [NSURL URLWithString:@"http://www.dyndns.org/cgi-bin/check_ip.cgi"];
    
    if (iPURL) {
        NSError *error = nil;
        NSString *theIpHtml = [NSString stringWithContentsOfURL:iPURL encoding:NSUTF8StringEncoding error:&error];
        if (!error) {
            NSScanner *theScanner;
            NSString *text = nil;
            
            theScanner = [NSScanner scannerWithString:theIpHtml];
            
            while ([theScanner isAtEnd] == NO) {
                
                // find start of tag
                [theScanner scanUpToString:@"<" intoString:NULL] ;
                
                // find end of tag
                [theScanner scanUpToString:@">" intoString:&text] ;
                
                // replace the found tag with a space
                //(you can filter multi-spaces out later if you wish)
                theIpHtml = [theIpHtml stringByReplacingOccurrencesOfString:
                             [ NSString stringWithFormat:@"%@>", text]
                                                                 withString:@" "] ;
                ipItemsArray =[theIpHtml  componentsSeparatedByString:@" "];
                an_Integer=[ipItemsArray indexOfObject:@"Address:"];
                externalIP =[ipItemsArray objectAtIndex:  ++an_Integer];
            }
            NSLog(@"%@",externalIP);
        } else {
            NSLog(@"Oops... g %ld, %@", (long)[error code], [error localizedDescription]);
        }
    }
    return externalIP;
}