Showing posts with label iPhone. Show all posts
Showing posts with label iPhone. Show all posts

Wednesday, August 19, 2015

working with UIMenuController

working with UIMenuController

I am creating menu on longPressGesture of some view.
The code is as below.

- (void)showMenu:(UILongPressGestureRecognizer *)gestureRecognizer
{
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan) {
        
        [self becomeFirstResponder];

        /*
         Set up th menu.
         */
        UIMenuItem *menuItem1 = [[UIMenuItem alloc] initWithTitle:@"Item 1" action:@selector(item1Selected:)];
        UIMenuItem *menuItem2 = [[UIMenuItem alloc] initWithTitle:@"Item 2" action:@selector(item2Selected:)];

        UIMenuController *menuController = [UIMenuController sharedMenuController];
        [menuController setMenuItems:@[menuItem1,menuItem2]];
        
        CGPoint location = [gestureRecognizer locationInView:[gestureRecognizer view]];
        CGRect menuLocation = CGRectMake(location.x, location.y, 0, 0);
        [menuController setTargetRect:menuLocation inView:[gestureRecognizer view]];
        
        [menuController setMenuVisible:YES animated:YES];
    }

}

- (void)item1Selected:(UIMenuController *)controller
{
    NSLog("Item 1 Selected");
}

- (void)item2Selected:(UIMenuController *)controller
{
    NSLog("Item 2 Selected");
}

// UIMenuController requires that we can become first responder or it won't display
- (BOOL)canBecomeFirstResponder
{
    return YES;
}

Saturday, June 27, 2015

Get color from touch point

Get color from touch point

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint loc = [touch locationInView:self.view];
    self.pickedColor = [self colorOfPoint:loc];
    self.theColor.backgroundColor = self.pickedColor;
}

-(UIColor *) colorOfPoint:(CGPoint)point {
    unsigned char pixel[4] = {0};
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, kCGImageAlphaPremultipliedLast);

    CGContextTranslateCTM(context, -point.x, -point.y);

    [self.view.layer renderInContext:context];

    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    UIColor *color = [UIColor colorWithRed:pixel[0]/255.0 green:pixel[1]/255.0 blue:pixel[2]/255.0 alpha:pixel[3]/255.0];

    return color;
}

Tuesday, June 16, 2015

Taking input from user via alert

Taking input from user via alert

UIAlertController * alert=   [UIAlertController alertControllerWithTitle:@"Text" message:@"Enter Text" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                               handler:^(UIAlertAction * action) {
                                                   //Do Some action here
                                                   UITextField *textField = alert.textFields.firstObject;
                                                   NSLog(@"%@",textField.text);
                                               }];
    UIAlertAction* cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault
                                                   handler:^(UIAlertAction * action) {
                                                       [alert dismissViewControllerAnimated:YES completion:nil];
                                                   }];
    
    [alert addAction:ok];
    [alert addAction:cancel];
    
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
                        textField.placeholder = @"Enter text here";
    }];
    

    [self presentViewController:alert animated:YES completion:nil];

Wednesday, April 22, 2015

Saving data in NSUserDefaults

Saving data in NSUserDefaults

If You want to save some details of user in device then you can use NSUserDefaults.
It just like SharedPreference or cookie.

To write data in NSUserDefaults use below code.

NSString *valueToSave = @"someValue";
[[NSUserDefaults standardUserDefaults] setObject:valueToSave forKey:@"myKey"];
[[NSUserDefaults standardUserDefaults] synchronize];

To read data from NSUserDefaults use below code.

NSString *savedValue = [[NSUserDefaults standardUserDefaults]
    stringForKey:@"myKey"];

Monday, February 16, 2015

Get User Current Location

Get User Current Location

  1. Import CoreLocation Framework to your Project
  2. #import <CoreLocation/CoreLocation.h> to your .h file
  3. Add CLLocationManagerDelegate to your .h file
  4. Now make object of CLLocationManager class
    e.g. 
    CLLocationManager *locationManager
  5. After this add following code to ViewDidLoad

    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [locationManager requestWhenInUseAuthorization];
    [locationManager requestAlwaysAuthorization];
    locationManager.distanceFilter=kCLDistanceFilterNone;    
    [locationManager startUpdatingLocation];
  6. Add two Delegate method to your .m file

    - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
    {
        NSLog(@"Latitude:%f Longitude:%f",newLocation.coordinate.latitude,newLocation.coordinate.longitude);
        
    [locationManager stopUpdatingLocation];
    }
    - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
    {
        
    }
  7. Add Properties to your info.plist file

    NSLocationAlwaysUsageDescription = location required
    NSLocationWhenInUseUsageDescription = Location is required to find out where you are
I got failure to get location because of not adding Property in Info.plist file.
In new versions of Xcode and iOS this is mandatory.

If you are testing in simulator then you have to put breakPoint before startUpdatingLocation and at the execution time you have to select city manually through Xcode. You can also add .GPX file for same.

Saturday, February 14, 2015

Share via Whatsapp in ios

Share via Whatsapp in ios

There are two method to share via whatsapp
  1. URL scheme
  2. Document Interaction API
If you want to go with URL Scheme
then here is example.

/**Just open whatsapp*/
NSURL *whatsappURL = [NSURL URLWithString:@"whatsapp://app"];
if ([[UIApplication sharedApplication] canOpenURL: whatsappURL]) {
    [[UIApplication sharedApplication] openURL: whatsappURL];
}

/** Send Hello World! to any contact/group*/
NSURL *whatsappURL = [NSURL URLWithString:@"whatsapp://send?text=Hello%2C%20World!"];
if ([[UIApplication sharedApplication] canOpenURL: whatsappURL]) {
    [[UIApplication sharedApplication] openURL: whatsappURL];
}

/** Send message to selected contact*/
NSURL *whatsappURL = [NSURL URLWithString:@"whatsapp://abid?/*Address Book ID*/"];
if ([[UIApplication sharedApplication] canOpenURL: whatsappURL]) {
    [[UIApplication sharedApplication] openURL: whatsappURL];
}

And if you want to go with Document Interaction API then check whatsapp documentation.

Monday, November 10, 2014

Image Loading and Caching

Image Loading and Caching


var imageCache = [String : UIImage]()


var image = self.imageCache[urlString]
       
       
        if( image == nil ) {
            // If the image does not exist, we need to download it
            var imgURL: NSURL = NSURL(string: urlString)
           
            // Download an NSData representation of the image at the URL
            let request: NSURLRequest = NSURLRequest(URL: imgURL)
            NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
                if error == nil {
                    image = UIImage(data: data)
                   
                    // Store the image in to our cache
                    self.imageCache[urlString] = image
                    dispatch_async(dispatch_get_main_queue(), {
                        if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) {
                            cellToUpdate.imageView?.image = image
                        }
                    })
                }
                else {
                    println("Error: \(error.localizedDescription)")
                }
            })
           
        }
        else {
            dispatch_async(dispatch_get_main_queue(), {
                if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) {
                    cellToUpdate.imageView?.image = image
                }
            })
        }



NOTE:This is in swift programming.

Tuesday, November 4, 2014

Toast message in iOS

Toast message in iOS

UIAlertView *toast = [[UIAlertView alloc] initWithTitle:nil message:@"Alert Example like toast" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
            [toast show];
            float duration = 0.5; // duration in seconds
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                [toast dismissWithClickedButtonIndex:0 animated:YES];

Monday, October 13, 2014

detecting iOS, iPhone, iPad and apple watch

detecting iOS, iPhone, iPad and apple watch

// detecting iOS


NSString *version = [[UIDevice currentDevice] systemVersion];
NSLog(@"Version:%@",version);

//detecting iPhone



add these line to your .h file

#define IS_IPHONE_4 (fabs((double)[[UIScreen mainScreen]bounds].size.height - (double)480) < DBL_EPSILON)
#define IS_IPHONE_5 (fabs((double)[[UIScreen mainScreen]bounds].size.height - (double)568) < DBL_EPSILON)
#define IS_IPHONE_6 (fabs((double)[[UIScreen mainScreen]bounds].size.height - (double)667) < DBL_EPSILON)
#define IS_IPHONE_6_PLUS (fabs((double)[[UIScreen mainScreen]bounds].size.height - (double)736) < DBL_EPSILON)


and use it in your .m file

if (IS_IPHONE_4)
        NSLog(@"iPhone 4");
else if (IS_IPHONE_5)
        NSLog(@"iPhone 5");

//detecting iPad


if ([UIDevice currentDevice].userInterfaceIdiom != UIUserInterfaceIdiomPad)
{
        //code for iPad
}

//detecting apple watch

add these line to your .h file

#define IS_WATCH_42 (fabs((double)self.contentFrame.size.height - (double)174) < DBL_EPSILON)

#define IS_WATCH_38 (fabs((double)self.contentFrame.size.height - (double)151) < DBL_EPSILON)


and use it in your .m file

if (IS_WATCH_42)
        NSLog(@"apple watch 42mm");
    else if (IS_WATCH_38)
        NSLog(@"apple watch 38mm");