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"];

Thursday, April 2, 2015

How to create Singleton in Objective c

How to create Singleton in Objective c

1)Add Class which inherits NSObject
2)Implement following in YourSingleton.h
                    
#import <foundation/Foundation.h>

@interface YourSingleton: NSObject {
    NSString *someProperty;
}

@property (nonatomic, retain) NSString *someProperty;

+ (id)sharedInstance;

@end
 
 
3)In YourSingleton.m
 
#import "YourSingleton.h"

@implementation YourSingleton

@synthesize someProperty;

#pragma mark Singleton Methods

+ (id)sharedInstance{
    static YourSingleton*sharedInstance= nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance= [[self alloc] init];
    });
    return sharedInstance;
}

- (id)init {
  if (self = [super init]) {
      someProperty = [[NSString alloc] initWithString:@"Default Property Value"];
  }
  return self;
}

- (void)dealloc {
  // Should never be called, but just here for clarity really.
}

@end
 
 
 
Its Done.....Now you can use it whenever you want. :)
 
 
 
Note : Do not user for creating UIkitcomponent because reference of instance of sigleton are never released.... 

Tuesday, March 24, 2015

Change font and size in watchkit

Change font and size in watchkit



  1. Create IBOutlet of your WKInterfaceLabel
  2. Create UIFont object

    UIFont
    * labelFont = [UIFont fontWithName:@"Courier-Bold" size:8];
  3. Create NSAttributedString object

    NSAttributedString *labelText = [[NSAttributedString alloc] initWithString : @"my Label string title" attributes : @{ NSKernAttributeName : @2.0, NSFontAttributeName : labelFont}];
  4. set attributedString to label

    [self.label setAttributedText:labelText];

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.

Sunday, November 16, 2014

Activity Indicator Tutorial (Storyboard)

Activity Indicator Tutorial (Storyboard)

Step 1 -
               Add 2 buttons to the main view and Give them a title of start and stop.
Step 2 -
              Add Activity Indicator to the center of the view.
              Select the Activity Indicator and go to the Attributes Inspector.
              Give the Activity Indicator a style of Large
              White and a color if yellow. select the "Hides when stopped" option.
Step 3 -
              Create Outlet in ViewController.m. and  IBAction Method

           ViewController.m

      @interface ViewController ()

      @property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityIndicatorView;

      - (IBAction)startSpinning:(UIButton *)sender;
      - (IBAction)stopSpinning:(UIButton *)sender;

     @end
 
 
   Implementing created method
 
     - (IBAction)startSpinning:(UIButton *)sender {
          [self.activityIndicatorView startAnimating];
     }

     - (IBAction)stopSpinning:(UIButton *)sender {
      [self.activityIndicatorView stopAnimating];
   } 

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.