Friday, November 28, 2014

Check Twitter Service availability on iOS Device



Add Social and Accounts framework:

 if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter]) {
   
   
    ACAccountStore *store = [[ACAccountStore alloc] init];
    ACAccountType *twitterType = [store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
    [store requestAccessToAccountsWithType:twitterType options:nil completion:^(BOOL granted, NSError *error) {
     
      if(error != nil) {
       
        NSLog(@"Twitter Error : %@", [error description]);
       
      } else {
       
        if(granted) {
         
          NSLog(@"Twitter permission granted");
         
        } else {
          NSLog(@"Twitter permission not granted");
        }
       
      }
     
    }];
   
  }
 

TouchID authentication in iOS


#import <LocalAuthentication/LocalAuthentication.h>


- (IBAction)authenicateButtonTapped:(id)sender {
 
  LAContext *context = [[LAContext alloc] init];
 
  NSError *error = nil;
 
  if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
   
    [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
            localizedReason:@"Are you the device owner?"
                      reply:^(BOOL success, NSError *error) {
                       
                       
                 
              dispatch_async(dispatch_get_main_queue(), ^{
                    // write all your code here
                 
                 
                  if (error) {
                   
                    if(error.code == kLAErrorUserFallback) {
                      [self passcodeFallback];
                    } else if(error.code == kLAErrorUserCancel) {
                      [self cancelLogin];
                    }
                   
                   
                    return;
                   
                  } else {
                 
                      if (success) {
                       
                        [self showAlertWithTitle:@"Success" andMessage:@"You are the device owner!"];

                       
                      } else {
                       
                        [self showAlertWithTitle:@"Error" andMessage:@"You are not the device owner."];

                      }
                  }
               
            });
                       
       }];

  } else {

   
    [self reportError];

   
  }
}


-(void)passcodeFallback {
  [self showAlertWithTitle:@"Error" andMessage:@"Show UI Screen to retrieve passcode from keychain"];

}

-(void)cancelLogin {
  [self showAlertWithTitle:@"Error" andMessage:@"Login Cancelled"];

}

-(void)reportError {
  [self showAlertWithTitle:@"Error" andMessage:@"Your deivice can't be authenticated"];
}


-(void)showAlertWithTitle:(NSString *)aTitle andMessage:(NSString *)aMsg {
 
 
  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:aTitle
                                                  message:aMsg
                                                 delegate:nil
                                        cancelButtonTitle:@"Ok"
                                        otherButtonTitles:nil];
  [alert show];
 
}

Thursday, November 27, 2014

UIDocumentInteractionController Example


- (void)onOpenWith:(UIButton *)theButton path:(NSString *)path
{  
    NSURL *URL = [NSURL fileURLWithPath:path];
  
    if (URL) {
        self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:URL];
      
        self.documentInteractionController.delegate = self;
      
        //self.documentInteractionController.name = @"Title";
        //self.documentInteractionController.UTI = @"com.adobe.pdf"; @"net.whatsapp.image";
      
        //Preview PDF
        //[self.documentInteractionController presentPreviewAnimated:YES];
              
        //Open In iBooks     
       //presentOpenInMenuFromRect
       //presentOptionsMenuFromRect
        [self.documentInteractionController presentOpenInMenuFromRect:CGRectZero
                                              inView:aView
                                            animated:YES];
    }
}


#pragma mark - UIDocumentInteractionControllerDelegate

- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller
{
    return self;
}

- (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller
{
    return self.view;
}

- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller
{
    return self.view.frame;
}

MPMoviePlayerViewController in Potrait and Landscape mode




- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)windowx
{
    if ([[self.window.rootViewController presentedViewController] isKindOfClass:[MPMoviePlayerViewController class]] ||
    [[self.window.rootViewController presentedViewController] isKindOfClass:NSClassFromString(@"MPInlineVideoFullscreenViewController")])
    {
        if ([self.window.rootViewController presentedViewController].isBeingDismissed)
        {
            return UIInterfaceOrientationMaskPortrait;
        }
        else
        {
            return UIInterfaceOrientationMaskAllButUpsideDown;
        }
    }
    else
    {
        return UIInterfaceOrientationMaskPortrait;
    }
}

Wednesday, November 26, 2014

iCloud Backup

Overview

iCloud includes Backup, which automatically backs up a user’s iOS device daily over Wi-Fi. Everything in your app’s home directory is backed up, with the exception of the application bundle itself, the caches directory, and temp directory. Purchased music, apps, books, the Camera Roll, device settings, home screen and app organization, messages, and ringtones are backed up as well. Because backups are done wirelessly and stored in iCloud for each user, it’s best to minimize the amount of data that’s stored for your app. Large files will lengthen the time it takes to perform a backup and consume more of a user’s available iCloud storage.

Storing Your App’s Data Efficiently

To ensure that backups are as efficient as possible, store your app’s data according to the following guidelines:
  1. Only documents and other data that is user-generated, or that cannot otherwise be recreated by your application, should be stored in the /Documents directory and will be automatically backed up by iCloud.
  2. Data that can be downloaded again or regenerated should be stored in the /Library/Caches directory. Examples of files you should put in the Caches directory include database cache files and downloadable content, such as that used by magazine, newspaper, and map applications.
  3. Data that is used only temporarily should be stored in the /tmp directory. Although these files are not backed up to iCloud, remember to delete those files when you are done with them so that they do not continue to consume space on the user’s device.
  4. Use the "do not back up" attribute for specifying files that should remain on device, even in low storage situations. Use this attribute with data that can be recreated but needs to persist even in low storage situations for proper functioning of your app or because customers expect it to be available during offline use. This attribute works on marked files regardless of what directory they are in, including the Documents directory. These files will not be purged and will not be included in the user's iCloud or iTunes backup. Because these files do use on-device storage space, your app is responsible for monitoring and purging these files periodically.

Excluding a File from Backup

- (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
{
    assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);

    NSError *error = nil;
    BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]
                                  forKey: NSURLIsExcludedFromBackupKey error: &error];

    if(!success){
        NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
    }
    return success;
}




Thursday, November 20, 2014

Speedup MacOS:

Delete Cache files:
~/Library/Caches

Delete Log Files:
~/Library/Logs
 

Wednesday, November 19, 2014

Reverse GeoCoding in iOS




#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>

@interface NearByViewController : UIViewController <CLLocationManagerDelegate>


@property (weak, nonatomic) IBOutlet UILabel *latLbl;
@property (weak, nonatomic) IBOutlet UILabel *lngLbl;
@property (weak, nonatomic) IBOutlet UILabel *addressLbl;


@end




//-------------------------------------------------------



#import "NearByViewController.h"


@interface NearByViewController () {
  CLLocationManager *locationManager;
}

@end

@implementation NearByViewController


-(void)initializeLocationManager {
  locationManager = [[CLLocationManager alloc] init];
  [locationManager setDelegate:self];
  [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
  [locationManager setDistanceFilter:100];
  [locationManager startUpdatingLocation];
 
  if([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]){
    [locationManager requestWhenInUseAuthorization]; // Add This Line
  }
 
  NSLog(@"Location Manager is initialised");
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
 
  [self initializeLocationManager];
}





#pragma mark - LocationManager Delegate

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations {
 
  /*
   if(currentLocation.latitude == 0.0 && currentLocation.longitude == 0.0) {
   currentLocation = manager.location.coordinate;
   NSLog(@"Latitude : %.2f, Longitude : %.2f", currentLocation.latitude, currentLocation.longitude);
  
   }
   */
 
 
  NSLog(@"Location manager didupdate in NearByViewController");
 
  CLLocation *currentLocation =    manager.location;
 
//  NSLog(@"Current Location 11 : %f , %f", currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);
 
 
  self.latLbl.text = [NSString stringWithFormat:@"%0.3f", currentLocation.coordinate.latitude];
  self.lngLbl.text = [NSString stringWithFormat:@"%0.3f", currentLocation.coordinate.longitude];
 
 
//  currentLocation = [locations lastObject];
//  NSLog(@"Current Location 22 : %f , %f", currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);

 
 
 
  [locationManager stopUpdatingLocation];
 
  CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
  [geoCoder reverseGeocodeLocation:[locations objectAtIndex:0] completionHandler:^(NSArray *placemarks, NSError *error) {
   
   
   
    CLPlacemark *placemark = [placemarks objectAtIndex:0];
   
    /*
    isoCountryCode.text      = placemark.ISOcountryCode;
    country.text          = placemark.country;
    postalCode.text          = placemark.postalCode;
    adminArea.text          = placemark.administrativeArea;
    subAdminArea.text      = placemark.subAdministrativeArea;
    locality.text          = placemark.locality;
    subLocality.text      = placemark.subLocality;
    thoroughfare.text      = placemark.thoroughfare;
    subThoroughfare.text  = placemark.subThoroughfare;
    */
   
    NSString *address = [NSString stringWithFormat:@"%@\n%@ %@\n%@\n%@",
                         placemark.thoroughfare,
                         placemark.postalCode, placemark.locality,
                         placemark.administrativeArea,
                         placemark.country];
   
    NSLog(@"Address : %@", address);
   
    self.addressLbl.text = address;
   
  }];
 
   
}


- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error {
  NSLog(@"Location Manager did fail : %@", [error localizedDescription]);
}


#pragma mark -


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end






Monday, November 17, 2014

Controlling Line Spacing using AttributedString

NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
style.lineSpacing = 17;
textView.attributedText = [[NSAttributedString alloc] 
    initWithString:@"Predefined Text" 
    attributes:@{NSParagraphStyleAttributeName : style}];
textView.text = @"Your text"
 
 
 

Monday, November 10, 2014

Formatting html at runtime:


1. Add custom font files in Proj.plist file
2. Insert the css styles at runtime.

NSString* htmlString = [NSString stringWithFormat:@"<html><head><style type=\"text/css\">"
                             @"@font-face {"
                             @"font-family: 'ITCAvantGardeStd-Bk';"
                             @"src: url('ITCAvantGardeStd-Bk.otf')  format('truetype')"
                             @"}"
                             @"@font-face {"
                             @"font-family: 'ITCAvantGardeStd-Bold';"
                             @"src: url('ITCAvantGardeStd-Bold.otf')  format('truetype')"
                             @"}"
                             @"body {"
                                @"font-family: ITCAvantGardeStd-Bk;"
                                @"font-size: 9pt;"
                                @"color: #969B9D"
                                @"}"
                             @"p{ font-family: 'ITCAvantGardeStd-Bk'; }"
                             @"strong {font-family: 'ITCAvantGardeStd-Bold';color:#5F656A;}"
                             @"</style></head><body>%@</body></html>",[self.contentDict1 objectForKey:@"bodyHTML"]];

Wednesday, November 5, 2014

Steps for fixing Macbook Pro issues:


Macbook HardDisk Repair/Format:
-----------------------------------------------
a) Create the bootable USB drive with Yosemite

(i) Format the USB drive with GUID Partition
(ii) Download Yosemite from AppStore and quit the installer.
(iii) Type the below command on MacOS Terminal

sudo /Applications/Install\ OS\ X\ Yosemite.app/Contents/Resources/createinstallmedia --volume /Volumes/Untitled --applicationpath /Applications/Install\ OS\ X\ Yosemite.app --nointeraction

b) Restart the Macbook and boot from USB Drive    

    (i) Hold down the Option key while rebooting
    (ii) Click on the USB drive icon to boot

    or ( Boot using Command + S , and then select USB as “Startup Disk” )


c) Format / Repair Disk the main HDD




Battery Repair ( Resetting the System Management Controller - SMC )
—————————----------------------------------------------------------------—
a) Shutdown the Macbook
b) Unplug the Power Cable
c) Remove the battery from Macbook , wait for 1 minute
d) Tap and hold the power on button for 5 seconds
e) Connect the battery back to Macbook
f) Reconnect the Power Cable and restart





Fix for trouble logging into MacOS:
----------------------------------------------
Steps:
(a) Hold Command + s and press Power On key
(b) #root: /sbin/mount -uw /
(c) #root: chmod 775 /
(d) #root: logout
(e) Hold Command + v while restarting





How To Reset PRAM:
=================

Step 1: Turn off your Mac. No need to remove the battery or detaching the power chord.

Step 2: Turn on your Mac and hold down the Command+Option+P+R keys, all at the same time.

Step 3: Hold down all four keys until you hear the startup sound twice.

The startup sound for the second time means you’ve reset the PRAM.







How To Reset SMC:
================

(a) For MacBooks With Removable Battery
---------------------------------------------------------
Step 1: Shut down the Mac, remove the back plate and disconnect the battery.

Step 2: Press and hold the power button for five seconds before releasing.

Step 3: Connect the battery and turn the Mac back on.



(b) For MacBooks Without Removable Battery
-------------------------------------------------------------
Step 1: Shut down the Mac and make sure it is plugged in to a power source.

Step 2: When the Mac is off, press and hold Shift+Control+Option keys as well as the Power button.

Step 3: Release all four keys at the same time. The Mac should not power on during this time.

Step 4: Press the power button to turn the Mac back on.




MacOS HardDisk Repair/Format



Steps:
--------

a) Create the bootable USB drive with Yosemite

(i) Format the USB drive with GUID Partition
(ii) Download Yosemite from AppStore and quit the installer.
(iii) Type the below command on MacOS Terminal

sudo /Applications/Install\ OS\ X\ Yosemite.app/Contents/Resources/createinstallmedia --volume /Volumes/Untitled --applicationpath /Applications/Install\ OS\ X\ Yosemite.app --nointeraction

b) Restart the Macbook and boot from USB Drive

c) Format / Repair Disk the main HDD

Resetting the System Management Controller (SMC)


1. Shut down the computer.
2. Disconnect the MagSafe power adapter from the computer, if it's connected.
3. Remove the battery.
4. Press and hold the power button for 5 seconds.
5. Release the power button.
6. Reconnect the battery and MagSafe power adapter.
7. Press the power button to turn on the computer.



Mac OS Booting Problem


Mac OS Booting Problem:
======================

Try the following commands to fix the booting problem in Mac OS X


Command + R       (Recovery Mode)

========================

Command + Shift + V

========================

Command + Option + P + R

hey!, try this method then 1.Shut down the computer. 2.Locate the following keys on the keyboard: Command, Option, P, and R. You will need to hold these keys down simultaneously in step 4. 3.Turn on the computer. 4.Press and hold the Command-Option-P-R keys. You must press this key combination before the gray screen appears. 5.Hold the keys down until the computer restarts and you hear the startup sound for the second time. 6.Release the keys and it should boot:)

===========================

Hey I repair macbook's, i get this problems some times, to fix this you just got to hold command + s then you get a black screen just wait until you see: root.
Then type /sbin/mount -uw /
Then type chmod 775 /
Then type logout and then it will boot after that, shut down your mac and then hold command + v and let it do it's work!

==========================================

UIAlertController Example


UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil
                                                               message:@"\n\n\n\n\n\n\n\n\n\n\n"             preferredStyle:UIAlertControllerStyleActionSheet];

__weak typeof(self) weakSelf = self;
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
    [weakSelf pickActionSheetFinishAction];
}];

[alertController addAction:cancelAction];
[alertController.view addSubview:self.topicPickView];
[self presentViewController:alertController animated:YES completion:nil];


=======================================================================


UIAlertController * searchActionSheet=[UIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];

[ searchActionSheet.view setBounds:CGRectMake(7, 180, self.view.frame.size.width, 470)];

//yourView represent the view that contains UIPickerView and toolbar
[searchActionSheet.view addSubview:self.yourView];
[self presentViewController:searchActionSheet animated:YES completion:nil];