Friday, 9 January 2015

iPhone Development: Post text or image to Whats-app in IOS

Whats-app, a common social platform gaining popularity very rapidly and now its time to let the app user's share contents from native apps to their whats-app friends. In our IOS app development we can share content with whats-app friends using two techniques provided by whats-app.

1. Throuhg cstom URL scheme.
2. Through UIDocumentInteractionController.


If you want to allow your app user to send text to a specific whats-app friend you can use custom URL scheme method.The custom URL provided by whats-app to open their app is whatsapp:// , you can send two parameter's in this abid and send  

abid = address book id of contact with which you want to start chat (if abid is not passed, then whats - app is opened with whats-app contact list)
send = initial text you want to send to specific contact

Below is the code example that shows how we can use it in our app

NSURL *whatsappURL = [NSURL URLWithString:@"whatsapp://send?text=Hello World!"];
if ([[UIApplication sharedApplication] canOpenURL: whatsappURL]) {
    [[UIApplication sharedApplication] openURL: whatsappURL];
}
Above code, first we create an url with whats-app url scheme and text we want to show on message box. Next we check if user has whats-app installed on his/her device. If its installed we will open whats-app url using openURL method of UIApplication.

Secondly, we can use UIDocumentationController to send image, audio, video to whats-app. Below is the code we use for sending image to whats-app
UIImage *whtsappImage = tempImageView.image; 
 NSString* imagePath = [NSString stringWithForma
t:@"%@/image.wai",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]];
 [[NSFileManager defaultManager] removeItemAtPath:imagePath error:nil];
 [UIImagePNGRepresentation(whtsappImage) writeToFile:imagePath atomically:YES];
 NSLog(@"image size: %@", NSStringFromCGSize(whtsappImage.size));
 UIDocumentInteractionController *_docController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:imagePath]];
 [_docController presentOpenInMenuFromRect:self.view.frame inView:self.view animated:YES];

In above code, we saved our image as .wai extension to our document directory and then add url or file path of saved image to UIDocumentController instance and present our UIDocumentController instance.

iOS-Copy from NSBUndle TO NSDocumentDirectory



Here is a code snippet  to Copy file from NSBUndle To NSDocumentDirectory


NSError *error;

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path])

{

NSString *bundle = [[NSBundle mainBundle] pathForResource:@”data” ofType:@”plist”];
[fileManager copyItemAtPath:bundle toPath: path error:&error];

}

Working with plist files programmatically



Next, look at this code which creates path to plist in documents directory:


NSError *error;

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1

NSString *documentsDirectory = [paths objectAtIndex:0]; //2

NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"]; //3
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]) //4

{

NSString *bundle = [[NSBundle mainBundle] pathForResource:@”data” ofType:@”plist”]; //5
[fileManager copyItemAtPath:bundle toPath: path error:&error]; //6

}

 
Read data:


NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
//load from savedStock example int value

int value;

value = [[savedStock objectForKey:@"value"] intValue];
[savedStock release];
And write data:
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];

 
//here add elements to data file

And write data to file

int value = 5;
[data setObject:[NSNumber numberWithInt:value] forKey:@”value”];
[data writeToFile: path atomically:YES];

Thumbnail from video- iOS


UIImageView*img=[[UIImageView alloc]initWithFrame:CGRectMake(140, -40, 200, 200)];
            AVURLAsset *asset1 = [[AVURLAsset alloc] initWithURL:msg.mediaURL options:nil];
            AVAssetImageGenerator *generate1 = [[AVAssetImageGenerator alloc] initWithAsset:asset1];
            generate1.appliesPreferredTrackTransform = YES;
            NSError *err = NULL;
            CMTime time = CMTimeMake(1, 2);
            CGImageRef oneRef = [generate1 copyCGImageAtTime:time actualTime:NULL error:&err];
            UIImage *one = [[UIImage alloc] initWithCGImage:oneRef];
            [img setImage:one];
            img.contentMode = UIViewContentModeScaleAspectFit;

Get IP Address -iOS Development


#include <ifaddrs.h>
#include <arpa/inet.h>

- (NSString *)getIPAddress {
    
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    NSString *wifiAddress = nil;
    NSString *cellAddress = nil;
    
    // retrieve the current interfaces - returns 0 on success
    if(!getifaddrs(&interfaces)) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            sa_family_t sa_type = temp_addr->ifa_addr->sa_family;
            if(sa_type == AF_INET || sa_type == AF_INET6) {
                NSString *name = [NSString stringWithUTF8String:temp_addr->ifa_name];
                NSString *addr = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)]; // pdp_ip0
                NSLog(@"NAME: \"%@\" addr: %@", name, addr); // see for yourself
                
                if([name isEqualToString:@"en0"]) {
                    // Interface is the wifi connection on the iPhone
                    wifiAddress = addr;
                } else
                    if([name isEqualToString:@"pdp_ip0"]) {
                        // Interface is the cell connection on the iPhone
                        cellAddress = addr;
                    }
            }
            temp_addr = temp_addr->ifa_next;
        }
        // Free memory
        freeifaddrs(interfaces);
    }
    NSString *addr = wifiAddress ? wifiAddress : cellAddress;
    return addr ? addr : @"0.0.0.0";
    
}

iPhone Development -3d animation to popup SubView




CAKeyframeAnimation *animation = [CAKeyframeAnimation
                                      animationWithKeyPath:@"transform"];
    
CATransform3D scale1 = CATransform3DMakeScale(0.5, 0.5, 1);  CATransform3D scale2 = CATransform3DMakeScale(1.2, 1.2, 1);
CATransform3D scale3 = CATransform3DMakeScale(0.9, 0.9, 1);
 CATransform3D scale4 = CATransform3DMakeScale(1.0, 1.0, 1);
    
NSArray *frameValues = [NSArray arrayWithObjects:
                            [NSValue valueWithCATransform3D:scale1],
                            [NSValue valueWithCATransform3D:scale2],
                            [NSValue valueWithCATransform3D:scale3],
                            [NSValue valueWithCATransform3D:scale4],
                            nil];
    [animation setValues:frameValues];
     
 NSArray *frameTimes = [NSArray arrayWithObjects:
                           [NSNumber numberWithFloat:0.0],
                           [NSNumber numberWithFloat:0.5],
                           [NSNumber numberWithFloat:0.9],
                           [NSNumber numberWithFloat:1.0],
                           nil];
    [animation setKeyTimes:frameTimes];
    
    animation.fillMode = kCAFillModeForwards;
    animation.removedOnCompletion = NO;
    animation.duration = .5;
    
    [signUpContainer.layer addAnimation:animation forKey:@"popup"];

iOS-Learning CocoaPods For beginners

 Hello guys, I was little scared about CocoaPods setups in xcode and using old way to integrate libraries from 3rd parties.

Without a dependency management tool, you might simply add each library’s code to your project. However, this has several disadvantages:
  • Wasting space.
  • There’s no central place where you can see all libraries that are available.
Difficult to find and update a library to a new version. Each time you have to download new update and integrate manually in xcode project.
 Here we go with just few steps:


1.) Open Terminal and type the following command:
 

  sudo gem update --system
 

Enter your password when requested. The Terminal output should look something like this:
Update may take a little while. Next, you need to install CocoaPods. Type this command in Terminal to do so:

 sudo gem install cocoapods

 
You may get this prompt during the install process:
 rake's executable "rake" conflicts with /usr/bin/rake
 Overwrite the executable? [yN]

If so, just enter y to continue. (This warning is raised because the rake gem is updated as part of the install process. You can safely ignore it.)



Lastly, enter this command in Terminal to complete the setup of CocoaPods:
 
pod setup

 
This process will likely take a while as this command clones the CocoaPods Specs repository into ~/.cocoapods/ on your computer.
Great, you’re now setup to use CocoaPods!


Installing Your First Dependency
Open Terminal and navigate to the directory containing your  project by using the cd command: 

cd ~/Path/To/Folder/Containing/Xcode Project

Next enter this command:
pod init

It will create a  Podfile for your project. The Podfile is where you define the dependencies your project re- lies on.

Type this command to open Podfile using Xcode for editing:

 open -a Xcode Podfile  

Replace# platform :ios, "6.0"with the following: 
 platform :ios, "7.0"
This tells CocoaPods that your project is targeting iOS 7. 

Type the following into your pod file, right after
target "ProjectName" do:
 pod 'AFNetworking', '2.2.1'

your pod command provided with 3rd party Libraries, it used.
Save and close the pod file. 

You now need to tell CocoaPods to “install” the dependencies for your project. Enter the following command in Termi- nal to do so (making sure that you’re still in the directory containing the ShowTracker project and Podfile):
pod install


You should see output similar to the following:


Analyzing dependencies...
Downloading dependencies...
Installing AFNetworking 2.1.1...
Generating Pods project
Integrating client project 
[!] From now on use `ProjectName.xcworkspace`.