How to share text and Image on WhatsApp in iOS

Sharing text and Images on WhatsApp is now possible through Open URL Scheme (deep linking).

Send Text –

NSString * msg = @"YOUR MSG";
NSString * urlWhats = [NSString stringWithFormat:@"whatsapp://send?text=%@",msg];
NSURL * whatsappURL = [NSURL URLWithString:[urlWhats stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
if ([[UIApplication sharedApplication] canOpenURL: whatsappURL]) {
    [[UIApplication sharedApplication] openURL: whatsappURL];
} else {
    // Cannot open whatsapp
}

Send Image –

— in .h file

@property (retain) UIDocumentInteractionController * documentInteractionController;

— in .m file

if ([[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:@"whatsapp://app"]]){

    UIImage     * iconImage = [UIImage imageNamed:@"YOUR IMAGE"];
    NSString    * savePath  = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/whatsAppTmp.jpg”];

    [UIImageJPEGRepresentation(iconImage, 1.0) writeToFile:savePath atomically:YES];

    _documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:savePath]];
    _documentInteractionController.UTI = @"net.whatsapp.image";
    _documentInteractionController.delegate = self;

    [_documentInteractionController presentOpenInMenuFromRect:CGRectMake(0, 0, 0, 0) inView:self.view animated: YES];

} else {
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"WhatsApp not installed." message:@“No WhatsApp installed." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}

You need add these lines in .plist file for iOS 9:

<key>LSApplicationQueriesSchemes</key>
<array>
<string>whatsapp</string>
</array>

How to show GPS strength value in iOS SDK

To show the signal strength of GPS we can use the properties of CLLocation like horizontalAccuracy and verticalAccuracy which indicate how accurate the device believes that location fix to be.

Here is some sample code –


if (someLocation.horizontalAccuracy < 0)
{
// No Signal
}
else if (someLocation.horizontalAccuracy > 163)
{
// Poor Signal
}
else if (someLocation.horizontalAccuracy > 48)
{
// Average Signal
}
else
{
// Full Signal
}

How to install “command line tools” with xcode 5.0.1

With Xcode 5.0.1 and Mavericks 10.9 the command line tools are no longer available via Xcode. There is only two ways to install command line tools.

1) Download directly from Apple developer downloads (https://developer.apple.com/downloads/index.action)

2) Using command line. Run this below command to install –

xcode-select --install

After you enter this command you’ll get a popup like below –

ZSTtJ

Just press Install and it will start downloading command line tools.. and you are good to go.

Create a folder inside documents directory in iOS apps

 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/MyFolder"];

if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
    [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder

iOS app security: Data Protection (Part 1)

Are you storing User’s credentials in app, Communicating with web services, getting user’s credit card details in your app? using in app purchases? If your answer is yes for any of these questions then you should seriously consider improving security of your application? Are you implementing proper security measures? if no then read on.. I am going to write a series of posts on iOS app security.

In this first post of this series I am going to explain how we can protect files which we are creating in our app.

iOS provides hardware-level encryption of files. Files marked for protection are encrypted using a per-device key, which is encrypted using the user’s password or PIN. Ten seconds after the device is locked, the unencrypted per-device key is removed from memory. When the user unlocks the device, the password or personal identification number (PIN) is used to decrypt the per-device key again, which is then used to decrypt the files.

You can configure the protection of files that you create with NSFileManager or NSData. The options, shown in the following list, have slightly different names. NSFileManager applies string attributes to the file, whereas NSData uses numeric options during creation, but the meanings are the same. The FileManager constants begin with NSFileProtection…, and the NSData constants begin with NSDataWritingFileProtection….

…None — The file is not protected and can be read or written at any time. This is the default value.

…Complete — Any file with this setting is protected ten seconds after the device is locked. This is the highest level of protection. Files with this setting may not be available when your program is running in the background. When the device is unlocked, these files are unprotected.

…CompleteUnlessOpen — Files with this setting are protected ten seconds after the device is locked unless they’re currently open. This allows your program to continue accessing the file while running in the background. When the file is closed, it will be protected if the device is locked.

…CompleteUntilFirstUserAuthentication — Files with this setting are protected only between the time the device boots and the first time the user unlocks the device. The files are unprotected from that point until the device is rebooted. This allows your application to open existing files while running in the background.

Sample usages with NSData –

 
[data writeToFile:path
             options:NSDataWritingFileProtectionComplete
               error:&error]

Sample usages with NSFileManager –

 
[[NSFileManager defaultManager] createFileAtPath:[self filePath]
                                        contents:[@"super secret file contents" dataUsingEncoding:NSUTF8StringEncoding]
                                      attributes:[NSDictionary dictionaryWithObject:NSFileProtectionComplete forKey:NSFileProtectionKey]];

If your application needs to know whether protected data is available, you can use one of the following:

– Implement the methods applicationProtectedDataWillBecomeUnavailable: and applicationProtectedDataDidBecomeAvailable: in your application delegate.

– Observe the notifications UIApplicationProtectedDataWillBecomeUnavailable and UIApplicationProtectedDataDidBecomeAvailable (these constants lack the traditional Notification suffix).

– Check[[UIApplication sharedApplication] protectedDataAvailable]

The weakest point in using file protection is that it depends on the 4 digit PIN user use, which offer only 10,000 combinations. Also if user is not using PIN then this won’t work at all.

Pro Tip –

The easiest way to create a protected file when you may or may not be in the background is as follows:

 
   [data writeToFile:path
             options:NSDataWritingFileProtectionComplete
               error:&error] ||
   [data writeToFile:path
             options:NSDataWritingFileProtectionCompleteUnlessOpen
               error:&error];

Note “||” between two statements.

If you use this technique, upgrade your file protection at startup with a routine like this:

 
-(void)upgradeFilesInDirectory:(NSString *)dir
                            error:(NSError **)error {
     NSFileManager *fm = [NSFileManager defaultManager];
     NSDirectoryEnumerator *dirEnum = [fm enumeratorAtPath:dir];
     for (NSString *path in dirEnum) {

		NSDictionary *attrs = [dirEnum fileAttributes];
		if (![[attrs objectForKey: NSFileProtectionKey]
    				isEqual:NSFileProtectionComplete]) {
			attrs = [NSDictionary dictionaryWithObject:NSFileProtectionComplete forKey:NSFileProtectionKey];
			[fm setAttributes:attrs ofItemAtPath:path error:error];
		}

	} 

}

File protection is very easy, simple and hardware-optimised, you should use this in every project of yours, unless you have a good reason to not to.

FacebookSDK/FacebookSDK.h file not found

If you are getting “FacebookSDK/FacebookSDK.h file not found” error, even if you have Facebook SDK included in your project? It might be possible that project is not able to access FacebookSDK because of some mis-configuration in references.

Your best bet to resolve this error is by  removing FacebookSDK.framework from your project and then start over with these steps. Re-linking the framework won’t help in many cases –

Step 1. Go to Build Phases in your Project Target.
Step 2. In Link Binary With Libraries, click the “+” button.
Step 3. Click on “Add Other…” button
Step 4. Browse your FacebookSDK folder. Generally in ~/Documents/FacebookSDK/
Step 5. Clik on (select) “FacebookSDK.framework” and then OPEN.

Hope this will save someone’s time!

Keyboard not working in iOS simulator?

If your keyboard (mac keyboard) is not working in the iPhone simulator you must have something wrong in iPhone Simulator preference file.

To fix the problem follow this –

0) Quit Xcode and simulator
1) Press ‘command+shift+g’ .. it will open the “go to folder” dialog.
2) type “~/Library/Preferences” in this dialog to go to your preference folder.
3) Delete “com.apple.iphonesimulator.plist” in this folder
4) Done. “com.apple.iphonesimulator.plist” will be regenerated when you start simulator again.

Alternatively you can also do this with just one command.

Open terminal and fire –

rm ~/Library/Preferences/com.apple.iphonesimulator.plist

This will do the trick in one step! Just make sure you quit Xcode and simulator before running this.

How to take screenshot programmatically in iOS SDK

First Import QuartzCore

#import <QuartzCore/QuartzCore.h>

Then –

if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
    UIGraphicsBeginImageContextWithOptions(self.window.bounds.size, NO, [UIScreen mainScreen].scale);
else
    UIGraphicsBeginImageContext(self.window.bounds.size);

[self.window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData * data = UIImagePNGRepresentation(image);
[data writeToFile:@"foo.png" atomically:YES];

Note that this won’t capture certain types of screen content, like OpenGL ES layers.

Check iOS version and write conditional code

I strongly recommend not to use iOS version numbers to write conditional code. There is usually a more reliable method of checking whether a particular feature available or not. But if you are in a deadly situation and hardly needed the version number then you can get iOS version number by UIDevice class. Here is the real code –


NSString *currSysVer = [[UIDevice currentDevice] systemVersion];

Here is how you can use this to write conditional code –


// A system version of 3.1 or greater is required to use CADisplayLink. The NSTimer
// class is used as fallback when it isn't available.
NSString *reqSysVer = @"3.1";
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending)
    displayLinkSupported = TRUE;

Above code works great but writing this condition is real pain every time. The solution of this is Macros. We can use Macros in objective c and reduce the line of code in above code.

Here is real code using Macros –

/*
 *  System Versioning Preprocessor Macros
 */ 

#define SYSTEM_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)


And how we can use these Macros to write conditional code –


/*
 *  Usage
 */ 

if (SYSTEM_VERSION_LESS_THAN(@"4.0")) {
    ...
}

if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"3.1.1")) {
    ...
}

Hope these Macros will save someone’s time.