Showing posts with label iOS programming. Show all posts
Showing posts with label iOS programming. Show all posts

Sunday, July 31, 2016

Local Notification in iOS 10 for Objective-C and Swift 3


The way you use to work with Local Notification in iOS 9 and below is completely different in iOS 10.

Below screen grab from Apple release notes depicts this.


Below is code for local notification :

Objective-C :

1. In App-delegate.h file use @import UserNotifications;
2. App-delegate should conform to UNUserNotificationCenterDelegate protocol
3. In didFinishLaunchingOptions use below code :

 UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
                          completionHandler:^(BOOL granted, NSError * _Nullable error) {
                              if (!error) {
                                  NSLog(@"request authorization succeeded!");
                                  [self showAlert];
                              }
                          }];

-(void)showAlert {
    UIAlertController *objAlertController = [UIAlertController alertControllerWithTitle:@"Alert" message:@"show an alert!" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction
                                   actionWithTitle:@"OK"
                                   style:UIAlertActionStyleCancel
                                   handler:^(UIAlertAction *action) {
                                       NSLog(@"Ok clicked!");
                                   }];
    [objAlertController addAction:cancelAction];
    
    
    [[[[[UIApplication sharedApplication] windows] objectAtIndex:0] rootViewController] presentViewController:objAlertController animated:YES completion:^{
        
    }];
    
}

4. Now create a button in any view controller and in IBAction use below code :

 UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];
    objNotificationContent.title = [NSString localizedUserNotificationStringForKey:@“Notification!” arguments:nil];
    objNotificationContent.body = [NSString localizedUserNotificationStringForKey:@“This is local notification message!“
                                                         arguments:nil];
    objNotificationContent.sound = [UNNotificationSound defaultSound];
    
    /// 4. update application icon badge number
    objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);
    
    // Deliver the notification in five seconds.
    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger
                                                  triggerWithTimeInterval:10.f repeats:NO];       
    
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@“ten”
                                                                          content:objNotificationContent trigger:trigger];
    /// 3. schedule localNotification
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        if (!error) {
            NSLog(@“Local Notification succeeded“);
        }
else {
    NSLog(@“Local Notification failed“);
}
    }];


Swift 3:

1. In App-delegate.h file use import UserNotifications
2. App-delegate should conform to UNUserNotificationCenterDelegate protocol
3. In didFinishLaunchingWithOptions use below code 

 // Override point for customization after application launch.
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
            // Enable or disable features based on authorization.
            if((error == nil)) {
                print(“Request authorization failed!")
            }
            else {
                print(“Request authorization succeeded!")
                self.showAlert()
            }
        }


func showAlert() {
        let objAlert = UIAlertController(title: "Alert", message: "Request authorization succeeded", preferredStyle: UIAlertControllerStyle.alert)
        
        objAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
        //self.presentViewController(objAlert, animated: true, completion: nil)
        
        UIApplication.shared().keyWindow?.rootViewController?.present(objAlert, animated: true, completion: nil)
    }


4. Now create a button in any view controller and in IBAction use below code :

let content = UNMutableNotificationContent()
        content.title = NSString.localizedUserNotificationString(forKey: "Hello!", arguments: nil)
        content.body = NSString.localizedUserNotificationString(forKey: "Hello_message_body", arguments: nil)
        content.sound = UNNotificationSound.default()
        content.categoryIdentifier = "notify-test"
        
        let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
        let request = UNNotificationRequest.init(identifier: "notify-test", content: content, trigger: trigger)
        
        let center = UNUserNotificationCenter.current()
        center.add(request)

Saturday, July 16, 2016

Regex for checking 10 digit mobile number


if([self validatePhone:searchBar.text])
   NSlog(“Valid mobile number”);   
else
   NSlog(“Invalid mobile number”);

- (BOOL)validatePhone:(NSString *)phoneNumber
{
   // NSString *phoneRegex = @"^((\\+)|(00))[0-9]{6,14}$";
    NSString * phoneRegex = @"^(\\+?)(\\d{10})$”;
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    
    return [phoneTest evaluateWithObject:phoneNumber];
}

-(BOOL) validateEmail:(NSString *)email
{
    NSString *emailRegex = @"^[^-._]+([A-Z0-9a-z]|([-._][^-._]))+[^-._]?@[A-Za-z0-9-]+\\.[A-Za-z]{2,4}$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];

}

Add INR ahead of price value Eg. INR. 1,000


 _lblPriceValue.text = [_ModelController.price changePriceformatAndAddUnit];

- (NSString *)changePriceformatAndAddUnit {
    return [NSString stringWithFormat:@“INR. %@", [self changePriceformat]];
}


- (NSString *)changePriceformat {
    int count = 0;
    long long int a = self.longLongValue;
    while (a != 0) {
        count++;
        a /= 10;
    }
    
    NSMutableString *string = [NSMutableString stringWithString:self];
    NSMutableString *newstring = [NSMutableString string];
    while (count > 3) {
        count -= 3;
        NSRange rang = NSMakeRange(string.length - 3, 3);
        NSString *str = [string substringWithRange:rang];
        [newstring insertString:str atIndex:0];
        [newstring insertString:@"," atIndex:0];
        [string deleteCharactersInRange:rang];
    }
    [newstring insertString:string atIndex:0];
    
    return newstring;

}

Sunday, September 6, 2015

iOS : Script for creating debug and release build folder

# START script for debugLib,releaselib device and simulator

LIB_TARGET_NAME="project-name"

if [ "${ACTION}" = "clean" ]
then
xcodebuild -target "$LIB_TARGET_NAME" -configuration ${CONFIGURATION} -sdk iphoneos clean
xcodebuild -target "$LIB_TARGET_NAME" -configuration ${CONFIGURATION} -sdk iphonesimulator clean
fi

if [ "${ACTION}" = "build" ]
then
xcodebuild -target "$LIB_TARGET_NAME" -configuration ${CONFIGURATION} -sdk iphoneos
xcodebuild -target "$LIB_TARGET_NAME" -configuration ${CONFIGURATION} -sdk iphonesimulator

ARM_FILES="${BUILD_DIR}/${CONFIGURATION}-iphoneos/lib${LIB_TARGET_NAME}.a"
ARM_FILES1="${BUILD_DIR}/Debug-iphoneos/lib${LIB_TARGET_NAME}.a"
I386_FILES="${BUILD_DIR}/${CONFIGURATION}-iphonesimulator/lib${LIB_TARGET_NAME}.a"

UNIVERSAL_OUTPUTFOLDER=${PROJECT_DIR}/build/${CONFIGURATION}-ProjectName

mkdir -p "${UNIVERSAL_OUTPUTFOLDER}"
echo "Creating library..."
if [ "${CONFIGURATION}" = "Release" ]
then
lipo -create "$ARM_FILES" -output "${UNIVERSAL_OUTPUTFOLDER}/lib${LIB_TARGET_NAME}${CONFIGURATION}.a"
else
lipo -create "$ARM_FILES1" "$I386_FILES" -output "${UNIVERSAL_OUTPUTFOLDER}/lib${LIB_TARGET_NAME}${CONFIGURATION}.a"
fi
cp -R "${BUILD_DIR}/${CONFIGURATION}-iphoneos/include" "${UNIVERSAL_OUTPUTFOLDER}/"
rm -rf "${PROJECT_DIR}/build/${CONFIGURATION}-iphoneos"
rm -rf "${PROJECT_DIR}/build/lib${LIB_TARGET_NAME}.build"
rm -rf "${PROJECT_DIR}/build/${CONFIGURATION}-iphonesimulator"
fi


# END script for debugLib,releaselib device and simulator

Create local notification in iOS

LocalNotification.h file :


#import <Foundation/Foundation.h>

@interface LocalNotification : NSObject

+ (LocalNotification*)standardLocalNotification;

- (void)scheduleAlert:(NSString*)alertBody;

- (void)scheduleAlert:(NSString*)alertBody fireDate:(NSDate*)fireDate;


@end

LocalNotification.m file :


#import <UIKit/UIKit.h>
#import "LocalNotification.h"

static LocalNotification*   localNotification = nil;

@interface LocalNotification(){
    UIApplication* application;
}

@end

@implementation LocalNotification

- (void)dealloc{
    [super dealloc];
}

- (instancetype)init{
    self = [super init];
    if (self) {
        application = [UIApplication sharedApplication];
    }
    return self;
}

+ (LocalNotification*)standardLocalNotification {

    @synchronized(self) {
        if(nil == localNotification) {
            localNotification = [LocalNotification alloc];
        }
    }
    return localNotification;
}

- (void)scheduleAlert:(NSString*)alertBody {

    [self scheduleAlert:alertBody fireDate:[[NSDate date] dateByAddingTimeInterval:1]];
}

- (void)scheduleAlert:(NSString*)alertBody fireDate:(NSDate*)fireDate{

    UILocalNotification* localNotification = [[UILocalNotification alloc] init];

    localNotification.fireDate = fireDate;
    localNotification.timeZone = [NSTimeZone systemTimeZone];
    localNotification.repeatInterval = 0;
    localNotification.soundName = UILocalNotificationDefaultSoundName;
    localNotification.alertBody = alertBody;

    [application scheduleLocalNotification:localNotification];
    [localNotification release];
}

@end

Tuesday, May 19, 2015

Status bar overlap view in iOS 7 and above

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        CGRect screen = [[UIScreen mainScreen] bounds];
        if (self.navigationController) {
            CGRect frame = self.navigationController.view.frame;
            frame.origin.y = 20;
            frame.size.height = screen.size.height - 20;
            self.navigationController.view.frame = frame;
        } else {
            if ([self respondsToSelector: @selector(containerView)]) {
                UIView *containerView = (UIView *)[self performSelector: @selector(containerView)];

                CGRect frame = containerView.frame;
                frame.origin.y = 20;
                frame.size.height = screen.size.height - 20;
                containerView.frame = frame;
            } else {
                CGRect frame = self.view.frame;
                frame.origin.y = 20;
                frame.size.height = screen.size.height - 20;
                self.view.frame = frame;
            }
        }
    }
}
Add this to make your status bar white just right after the  [self.window makeKeyAndVisible];  in App delegate file
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}