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
}

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

What is the difference among nil, NULL, Nil in Objective-C?

They are all zeros, the difference lies in their types

-> NULL is a generic pointer value ((void*)0, to be specific). It points to 0x0.
-> nil is an id. So its points to a non-existent objective-c object
-> Nil is a non-existent objective-c class
-> [NSNull null] is an object that’s meant to stand in for nil in situations where nil isn’t allowed. For example, you can’t have a nil value in an NSArray. So if you need to represent a “nil”, you can use [NSNull null]

Also there is no ‘null’ in the objective c its ‘NULL’ not ‘null’. ‘null’ exist in Java or in C# not in Objective-C

Variable number of arguments in Objective-C methods

Ever wondered how the NSString’s +stringWithFormat: method work? How you can pass endless arguments in it?

Well methods that take variable arguments are known as variadic methods.

Here is an example of such a method

Declare variable argument function in your .h file as below

- (void) appendObjects:(id) firstObject, ...; // This method takes a nil-terminated list of objects.

Here is the definition in .m file –

- (void) appendObjects:(id) firstObject, ...
{
     id eachObject;
     va_list argumentList;
     if (firstObject) // The first argument isn't part of the varargs list,
     {                                   
           [self addObject: firstObject];// so we'll handle it separately.
           va_start(argumentList, firstObject); // Start scanning for arguments after firstObject.
           while (eachObject = va_arg(argumentList, id)) // As many times as we can get an argument of type "id"
           {
               [self addObject: eachObject]; // that isn't nil, add it to self's contents.
           }
           va_end(argumentList);

     }

}

iOS development learning resources

Here is a good compilation of links useful in learning iOS development

1) Blogs on iPhone development
http://www.cimgf.com/
http://mycodeteacher.com/
http://iphonedevelopment.blogspot.com/
http://iphoneincubator.com/blog/
http://iphone.zcentric.com/
http://iphoneproghelp.blogspot.com/ (Programming Tutorial)
http://icodeblog.com/ (Programming Tutorial)
http://idevrecipes.com/

2) iPhone Source Code
http://www.theiphonedev.com/SourceCode/tabid/143/Default.aspx

3) Community
http://www.iphonekicks.com/
https://devforums.apple.com/
http://iphonedevsdk.com/

4) News
http://mobileorchard.com/
http://theappleblog.com/

5) Jail breaking/Hacking
http://theiphoneproject.org/

6) Open source libraries and Applications
http://www.codingventures.com/2008/12/useful-open-source-libraries-for-iphone-development/#more-43
http://www.sourcemac.com/
http://www.codeplex.com/
Face Detection: http://niw.at/articles/2009/03/14/using-opencv-on-iphone/en
Bar Code: Is there a barcode recognition framework for iOS?
Rating: http://github.com/eisernWolf/TouchCustoms
http://github.com/erica/iphone-3.0-cookbook-
Is there a gallery of reusable iPhone components on the web?
http://mattgemmell.com/source
http://www.cocoacontrols.com/
http://open.iphonedev.com/
http://www.opensourceresources.org/
http://www.raywenderlich.com/tag/sample-code
Three 20: http://github.com/facebook/three20
Tapku Library: http://github.com/devinross/tapkulibrary

7) Topic-wise
App Store: https://developer.apple.com/appstore/resources/approval/guidelines.html
GIF Support: http://stackoverflow.com/questions/1379818/how-can-i-make-an-animated-gif-with-the-iphone-sdk
In App Purchase: http://www.sixtemia.com/journal/2009/08/12/using-store-kit-framework/
IP Address: http://www.iphonedevsdk.com/forum/iphone-sdk-development/5293-get-current-ip-address.html
Page Curl Animation: What iPhone OS APIs could I use to implement a transition animation similar to the iBook page flip transition?
TTF Font http://github.com/zynga/FontLabel
Rotate Label: http://iphonedevelopment.blogspot.com/2009/12/better-two-finger-rotate-gesture.html
Speech Recognition – 1: http://cmusphinx.sourceforge.net/
Speech Recognition – 2: http://www.politepix.com/openears/
Operation and Thread: http://www.cimgf.com/2008/02/16/cocoa-tutorial-nsoperation-and-nsoperationqueue/
Web service: http://icodeblog.com/2008/11/03/iphone-programming-tutorial-intro-to-soap-web-services/
Code Analyzer: http://clang.llvm.org/StaticAnalysis.html
Game Center: http://mobile.tutsplus.com/tutorials/iphone/ios-sdk-game-center-achievements-and-leaderboards-part-1/
SMS Chat: https://github.com/acani/AcaniChat
Rotating Knob: https://github.com/hollance/MHRotaryKnob

8 ) Game Development with Cocos2D
http://code.google.com/p/cocos2d-iphone/
http://blog.sapusmedia.com/search/label/cocos2d
http://iphonesdkdev.blogspot.com/2009/01/xcode-template-for-cocos2d.html
http://monoclestudios.com/cocos2d_whitepaper.ht
http://lethain.com/entry/2008/oct/03/notes-on-cocos2d-iphone-development/
http://lethain.com/entry/2008/oct/20/touch-detection-in-cocos2d-iphone/
Open GL: http://web.me.com/smaurice/AppleCoder/iPhone_OpenGL/Archive.html

9) Drawing Charts and Graphs
http://code.google.com/p/core-plot/
http://code.google.com/p/s7graphview/
http://github.com/duivesteyn-enterprises/deSimpleChart
http://www.rgraph.net/ (Will work on UIWebView only)
http://sebkade.wordpress.com/2010/05/06/basic-graph-class-for-iphone/ (a blog where demo is given to create a graph)

10) Map Kit
http://github.com/kishikawakatsumi/MapKit-Route-Directions
http://www.iphonedevsdk.com/forum/iphone-sdk-development/8100-opening-maps-app-given-route-direction.html
http://spitzkoff.com/craig/?p=65

11) Audio Streaming
http://code.google.com/p/indie1031/
http://cocoawithlove.com/2010/03/streaming-mp3aac-audio-again.html
http://code.google.com/p/audiostreamer-meta/
http://github.com/DigitalDJ/AudioStreamer
http://lists.apple.com/archives/coreaudio-api/2009/Jan//msg00143.html
https://bitbucket.org/brentsimmons/ngmovieplayer/ (It’s a code for streaming video using     AVPlayer class. Same code could be applied for streaming audio as well by minor modification)

12) Twitter
http://code.google.com/p/tweetphoto-api-objective-c/
http://tweetphoto-api-objective-c.googlecode.com/files/TweetPhoto.zip

13) Scroll View
http://github.com/andreyvit/ScrollingMadness

14) SQLite
http://code.google.com/p/sqlitepersistentobjects/

15) Video
How to play YouTube Movie on an iPhone Application when tapped on UITableViewCell?
http://www.iphonedevsdk.com/forum/iphone-sdk-development/41322-convert-image-sequences-video.html

16) SCM
http://iphonedevelopment.blogspot.com/2009/03/version-control-is-your-friend.html
http://developer.apple.com/tools/subversionxcode.html
Which SCM system for Xcode?
http://www.covertapps.com/development/6-setting-up-your-xcode-scm-repositories

17) Testing: Functional Testing
http://www.gorillalogic.com/fonemonkey
Unit Testing:
i) http://code.google.com/p/google-toolbox-for-mac/
ii)http://developer.apple.com/tools/unittest.html
Automated Testing:
i) http://cocoawithlove.com/2008/11/automated-user-interface-testing-on.html
ii)http://code.google.com/p/uispec/
iii) http://answers.oreilly.com/topic/1646-how-to-use-uiautomation-to-create-iphone-ui-tests/

18) Push Notification
http://blog.boxedice.com/2009/07/10/how-to-build-an-apple-push-notification-provider-server-tutorial/
http://urbanairship.com/

19) Core Data Tutorial for Beginners
http://www.raywenderlich.com/934/core-data-tutorial-getting-started

20) VOIP
http://code.google.com/p/idoubs/
http://code.google.com/p/siphon/
http://github.com/pzion/miumiu
http://www.linphone.org/eng/download/git.html

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.

Disable multitasking support in iOS 4 app

You can disable multitasking in iOS 4+ app just by adding a ‘UIApplicationExitsOnSuspend’ key in your info.plist file.

Multitasking support is enabled by default in all iOS 4+ application. There can be situations where you need to disable this support (if you don’t want your app to run in background).
You can disable multitasking in iOS 4+ app just by adding a key in your info.plist file.

You just need to add this following key (right click on your info.plist file and open as plain text file) –

<key>UIApplicationExitsOnSuspend</key>
	<true/> 

If you are using visual editor to edit info.plist file the just click on “+” button and add ‘UIApplicationExitsOnSuspend’ key and press tab key and select the check mark.

NSString Format Specifiers

Do you ever got confused when you want to NSLog a long integer? What to use to print a long %ld or %lx or %f or %d. Well Here is a complete list of all the NSString format specifiers

Do you ever got confused when you want to NSLog a long integer? What to use to print a long %ld or %lx or %f or %d. Well Here is a complete list of all the NSString format specifiers –

Specifier Description
%@ Objective-C object, printed as the string returned by descriptionWithLocale: if available, or description otherwise. Also works with CFTypeRef objects, returning the result of the CFCopyDescription function.
%% '%' character
%d, %D, %i Signed 32-bit integer (int)
%u, %U Unsigned 32-bit integer (unsigned int)
%hi Signed 16-bit integer (short)
%hu Unsigned 16-bit integer (unsigned short)
%qi Signed 64-bit integer (long long)
%qu Unsigned 64-bit integer (unsigned long long)
%x Unsigned 32-bit integer (unsigned int), printed in hexadecimal using the digits 0–9 and lowercase a–f
%X Unsigned 32-bit integer (unsigned int), printed in hexadecimal using the digits 0–9 and uppercase A–F
%qx Unsigned 64-bit integer (unsigned long long), printed in hexadecimal using the digits 0–9 and lowercase a–f
%qX Unsigned 64-bit integer (unsigned long long), printed in hexadecimal using the digits 0–9 and uppercase A–F
%o, %O Unsigned 32-bit integer (unsigned int), printed in octal
%f 64-bit floating-point number (double)
%e 64-bit floating-point number (double), printed in scientific notation using a lowercase e to introduce the exponent
%E 64-bit floating-point number (double), printed in scientific notation using an uppercase E to introduce the exponent
%g 64-bit floating-point number (double), printed in the style of %e if the exponent is less than –4 or greater than or equal to the precision, in the style of %f otherwise
%G 64-bit floating-point number (double), printed in the style of %E if the exponent is less than –4 or greater than or equal to the precision, in the style of %f otherwise
%c 8-bit unsigned character (unsigned char), printed by NSLog() as an ASCII character, or, if not an ASCII character, in the octal format \ddd or the Unicode hexadecimal format \udddd, where d is a digit
%C 16-bit Unicode character (unichar), printed by NSLog() as an ASCII character, or, if not an ASCII character, in the octal format \ddd or the Unicode hexadecimal format \udddd, where d is a digit
%s Null-terminated array of 8-bit unsigned characters. %s interprets its input in the system encoding rather than, for example, UTF-8.
%S Null-terminated array of 16-bit Unicode characters
%p Void pointer (void *), printed in hexadecimal with the digits 0–9 and lowercase a–f, with a leading 0x
%L Length modifier specifying that a following a, A, e, E, f, F, g, or G conversion specifier applies to a long double argument
%a 64-bit floating-point number (double), printed in scientific notation with a leading 0x and one hexadecimal digit before the decimal point using a lowercase p to introduce the exponent
%A 64-bit floating-point number (double), printed in scientific notation with a leading 0X and one hexadecimal digit before the decimal point using a uppercase P to introduce the exponent
%F 64-bit floating-point number (double), printed in decimal notation
%z Length modifier specifying that a following d, i, o, u, x, or X conversion specifier applies to a size_t or the corresponding signed integer type argument
%t Length modifier specifying that a following d, i, o, u, x, or X conversion specifier applies to a ptrdiff_t or the corresponding unsigned integer type argument
%j Length modifier specifying that a following d, i, o, u, x, or X conversion specifier applies to a intmax_t or uintmax_t argument

Hope it will save someone time!