Make Better Things



I like to make better things.

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>

Automatic Reference Counting (ARC) in Xcode 4.2

Xcode 4.2 now includes a new feature called Automatic Reference Counting aka. ARC which automates memory management for Objective-C objects. ARC makes memory management much easier, greatly reducing the chance that your program will have memory leaks. First, Xcode reviews your project to determine whether there are items that cannot be converted (and that you must therefore change manually). Then, Xcode rewrites your source code to use ARC.

ARC works by adding code at compile time to ensure that objects live as long as necessary, but no longer. Conceptually, it follows the same memory management conventions as manual reference counting, by adding the appropriate retain, release, and autorelease method calls for you.

ARC is supported in Xcode 4.2 for Mac OS X v10.6 and v10.7 (64-bit applications) and for iOS 4 and iOS 5. Weak references are not supported in Mac OS X v10.6 and iOS 4.

Instead of you having to remember when to use retain, release, and autorelease, ARC evaluates the lifetime requirements of your objects and automatically inserts the appropriate method calls for you at compile time. The compiler also generates appropriate dealloc methods for you. In general, if you’re only using ARC the traditional Cocoa naming conventions are important only if you need to interoperate with code that uses manual reference counting.

A complete and correct implementation of a Person class might look like this:

@interface Person : NSObject
@property (nonatomic, strong) NSString *firstName;
@property (nonatomic, strong) NSString *lastName;
@property (nonatomic, strong) NSNumber *yearOfBirth;
@property (nonatomic, strong) Person *spouse;
@end

@implementation Person
@synthesize firstName, lastName, yearOfBirth, spouse;
@end

Using ARC, you could implement a contrived method like this:

- (void)contrived {
    Person *aPerson = [[Person alloc] init];
    [aPerson setFirstName:@"William"];
    [aPerson setLastName:@"Dudney"];
    [aPerson:setYearOfBirth:[[NSNumber alloc] initWithInteger:2011]];
    NSLog(@"aPerson: %@", aPerson);
}

ARC takes care of memory management so that neither the Person nor the NSNumber objects are leaked.

You could also safely implement a takeLastNameFrom: method of Person like this:

- (void)takeLastNameFrom:(Person *)person {
    NSString *oldLastname = [self lastName];
    [self setLastName:[person lastName]];
    NSLog(@"Lastname changed from %@ to %@", oldLastname, [self lastName]);
}

ARC ensures that oldLastName is not deallocated before the NSLog statement.

ARC Enforces New Rules
To work, ARC imposes some new rules that are not present when using other compiler modes. The rules are intended to provide a fully reliable memory management model; in some cases, they simply enforce best practice, in some others they simplify your code or are obvious corollaries of your not having to deal with memory management. If you violate these rules, you get an immediate compile-time error, not a subtle bug that may become apparent at runtime.

  • You cannot explicitly invoke dealloc, or implement or invoke retain, release, retainCount, or autorelease.The prohibition extends to using @selector(retain), @selector(release), and so on.

    You may implement a dealloc method if you need to manage resources other than releasing instance variables. You do not have to (indeed you cannot) release instance variables, but you may need to invoke [systemClassInstance setDelegate:nil] on system classes and other code that isn’t compiled using ARC.

    Custom dealloc methods in ARC do not require a call to [super dealloc] (it actually results in a compiler error). The chaining to super is automated and enforced by the compiler.

    You can still use CFRetain, CFRelease, and other related functions with Core Foundation-style objects (see “Managing Toll-Free Bridging”).

  • You cannot use NSAllocateObject or NSDeallocateObject.You create objects using alloc; the runtime takes care of deallocating objects.
  • You cannot use object pointers in C structures.Rather than using a struct, you can create an Objective-C class to manage the data instead.
  • There is no casual casting between id and void *.You must use special casts that tell the compiler about object lifetime. You need to do this to cast between Objective-C objects and Core Foundation types that you pass as function arguments. For more details, see “Managing Toll-Free Bridging”.
  • Cannot use NSAutoreleasePool objects.ARC provides @autoreleasepool blocks instead. These have an advantage of being more efficient than NSAutoreleasePool.
  • You cannot use memory zones. There is no need to use NSZone any more—they are ignored by the modern Objective-C runtime anyway.

To allow interoperation with manual retain-release code, ARC imposes some constraints on method and variable naming:

You cannot give a property a name that begins with new.

Singleton Design Pattern for Objective-C

Well first of all what is a singleton design pattern -

A singleton class in an object-oriented application always returns the same instance of itself. It provides a global access point for the resources provided by the object of the class. A design pattern that is related to these kinds of designs is called the Singleton pattern.

When Would You Use the Singleton Pattern?

  • There must be exactly one instance of a class with which it must be accessible from a well-known access point.
  • The sole instance can be extended only by subclassing, and it won’t break client code with the extended object.

The Singleton pattern provides a well-known access point to client classes that want to create a unique instance of and access to a shared resource. Although a static global object reference or a class method can provide a global access point, the global object cannot prevent the class getting instantiated more than once, and the class method lacks the flexibility of decoupling.

A static global variable holds a single reference to an instance of a class. Another class or a method that can access that global variable is, in fact, sharing the same copy with other classes or methods that use the same variable. That sounds like what we are after in this chapter. Everything seems fine if we use only the same global variable throughout the whole application. So, in fact, we don’t need the Singleton pattern. But hey, wait a minute; what if there is somebody in your team or a consultant who has defined the same type of static global variable as yours? Then there will be two copies of the same global object type living in the same application—so a global variable doesn’t really solve the problem.

A class method provides shared services without creating an object of it. A single instance of the resource is maintained within the class method. However, this approach lacks the flexibility if the class needs to be subclassed to provide better services.

A singleton class can guarantee a single, consistent, and well-known access point to create and access a single object of the class. The pattern provides the flexibility such that any of its subclasses can override the instance method and have total control over object creation of itself without changing code in the client. Or even better, the instance implementation in the parent class can handle dynamic object creation. The actual type of a class can be determined to make sure the correct object is created at runtime. This technique will be discussed later in the chapter.

Implementing a Singleton in Objective-C -

MySingleton.h
#import <Foundation/Foundation.h>

@interface MySingleton : NSObject {

}

+ (MySingleton*) sharedInstance;

@end

MySingleton.m


#import "MySingleton.h"

static MySingleton *_instance;
@implementation MySingleton

#pragma mark -
#pragma mark Singleton Methods

+ (MySingleton*)sharedInstance
{
 @synchronized(self) {

 if (_instance == nil) {

 _instance = [[self alloc] init];

 // Allocate/initialize any member variables of the singleton class here
 // example
 //_instance.member = @"";
 }
 }
 return _instance;
}

+ (id)allocWithZone:(NSZone *)zone

{    
 @synchronized(self) {

 if (_instance == nil) {

 _instance = [super allocWithZone:zone];            
 return _instance;  // assignment and return on first allocation
 }
 }

 return nil; //on subsequent allocation attempts return nil    
}

- (id)copyWithZone:(NSZone *)zone
{
 return self;    
}

- (id)retain
{    
 return self;    
}

- (unsigned)retainCount
{
 return UINT_MAX;  //denotes an object that cannot be released
}

- (void)release
{
 //do nothing
}

- (id)autorelease
{
 return self;    
}

#pragma mark -
#pragma mark Custom Methods

// Add your custom methods here

@end

Visit Apple doc's this page for more info on Singleton Design Pattern -
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html