Thursday, 28 November 2013

How to get device IPAddess in Objective C

#include <arpa/inet.h>
#include <netdb.h>
#include <net/if.h>
#include <ifaddrs.h>


// retun the host name
+ (NSString *) hostname
{
    char baseHostName[256]; 
    int success = gethostname(baseHostName, 255);
    if (success != 0) return nil;
    baseHostName[255] = '\0';
    
#if !TARGET_IPHONE_SIMULATOR
    return [NSString stringWithFormat:@"%s.local", baseHostName];
#else
     return [NSString stringWithFormat:@"%s", baseHostName];
#endif
}

// return IP Address
+ (NSString *) localIPAddress
{
    struct hostent *host = gethostbyname([[self hostname] UTF8String]);
    if (!host) {herror("resolv"); return nil;}
    struct in_addr **list = (struct in_addr **)host->h_addr_list;
    return [NSString stringWithCString:inet_ntoa(*list[0]) encoding:NSUTF8StringEncoding];
}

In Objective-C Generates alpha-numeric-random string





// Generates alpha numeric random string
- (NSString *)genRandomStringLength:(int)Len {
    static NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    NSMutableString *randomString = [NSMutableString stringWithCapacity: len];
    for (int i=0; i<len; i++) {
        [randomString appendFormat: @"%C", [letters characterAtIndex: arc4random() % [letters length]]];
    }
    return randomString;
}

Wednesday, 27 November 2013

Create your own Objective-C Delegate Protocol

To create your own custom delegate protocol, you need to modify the header file for the selected class to then add the @protocol declaration, a delegate @property, and declare the methods that delegates can implement:

Please note; this tutorial is written on the understanding that you have basic to moderate knowledge in the iOS Application Development language: Objective-C. If this is not the case then I suggest that you read Objective-C book to further develop your knowledge and ensure you can successfully follow on with this tutorial.


// YourViewController.h: 

#import <UIKit/UIKit.h>

@protocol YourProtocolName

@interface YourViewController: UIViewController

@property (nonatomic, weak)id<YourProtocolName> delegate;
@end
@protocol YourProtocolName <NSObject>

@required

-(void)requiredDelegateMethod;

@optional
-(void)optionalDelegateMethodOne;
-(void)optionalDelegateMethodTwo:(NSString *)withArgument;


@end 
// end of delegate protocol


Next, In the implementation file, anytime you want to call the delegate method, you first need to check and see if the delegate is set, and then if it responds to the selector. Once this is checked, then you can call the method, for this we are going to use an if statement:
if (self.delegate && [self.delegate respondsToSelector:@selector(optionalDelegateMethodOne)])
{
    [self.delegate optionalDelegateMethodOne];
}

Now for classes you want to conform to your new protocol, include the header file and delegate protocol in the @interface:
#include "YourViewController.h"  
// needed to include the @delegate protocol info


@interface FavoritesViewController : UIViewController <YourProtocolName>


Finally, any required delegate methods must then be implemented in your class’s @implementation file.

I thought it worth while to explain that the first @protocol line in the header is only needed if the actual protocol comes after the @interface@end code.
So this works as well





// YourViewController.h:

#import <UIKit/UIKit.h>

@protocol YourProtocolName <NSObject>
@required
-(void)requiredDelegateMethod;

@optional
-(void)optionalDelegateMethodOne;
-(void)optionalDelegateMethodTwo:(NSString *)withArgument;

@end // end of delegate protocol

@interface YourViewController: UIViewController

@property (nonatomic, weak) id<YourProtocolName> delegate;



@end

Friday, 15 November 2013

Determine exact version of device software is running on.

Step 1 : -first create a NSObject class.

//
// NameofClass.h
//
#import <Foundation/Foundation.h> @interface NameOfClass : NSObject + (NSString *) Platform; + (NSString *) PlatformString; @end



//
// NameofClass.m
//
#import "NameOfClass.m"
#include <sys/types.h>
#include <sys/sysctl.h>
@implementation NameOfClass
 
+ (NSString *) Platform{
size_t size;
sysctlbyname("hw.machine", NULL, &size, NULL, 0);
char *machine = malloc(size);
sysctlbyname("hw.machine", machine, &size, NULL, 0);
NSString *platform = [NSString stringWithUTF8String:machine];
free(machine);
return platform;
}
 
+ (NSString *) PlatformString{
NSString *platform = [self platform];
if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 1G";
if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
if ([platform isEqualToString:@"iPhone3,3"]) return @"Verizon iPhone 4";
if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
if ([platform isEqualToString:@"iPod1,1"]) return @"iPod Touch 1G";
if ([platform isEqualToString:@"iPod2,1"]) return @"iPod Touch 2G";
if ([platform isEqualToString:@"iPod3,1"]) return @"iPod Touch 3G";
if ([platform isEqualToString:@"iPod4,1"]) return @"iPod Touch 4G";
if ([platform isEqualToString:@"iPad1,1"]) return @"iPad";
if ([platform isEqualToString:@"iPad2,1"]) return @"iPad 2 (WiFi)";
if ([platform isEqualToString:@"iPad2,2"]) return @"iPad 2 (GSM)";
if ([platform isEqualToString:@"iPad2,3"]) return @"iPad 2 (CDMA)";
if ([platform isEqualToString:@"i386"]) return @"Simulator";
if ([platform isEqualToString:@"x86_64"]) return @"Simulator";
return platform;
}
 
@end

Wednesday, 13 November 2013

Xcode Shortcuts

How to upload images using ASIHttpRequest ?

This example shows how to upload images using iPhone SDK. In this example we pick multiple images from iPhone Image Gallery or from iPhone Camera and send them to server using ASIHttpRequest.
Step 1 :- Download Latest version of the AsiHttp framework.
Step 2 :- Copy the Folder of ASI and paste in to your project.
Step 3 :- Following Framework import into your projects.

  • SystemConfiguration.framework
  • MobileCoreServices.framework
  • CoreGraphics.framework
  • libz.1.2.3.dylib

    Then start placing code as follows into your project.Code for .h file.
    @interface RootViewController : UIViewController
    {
        NSMutableArray *arrImages;
        IBOutlet UIButton *btnImage1;
        IBOutlet UIButton *btnImage2;
        IBOutlet UIButton *btnImage3;
        IBOutlet UIButton *btnImage4;
    }
    - (IBAction)btnTakePicture_Clicked:(id)sender;
    - (IBAction)btnPostImages_Clicked:(id)sender;
    Code for .m file.
    #import "RootViewController.h"
    #import "ASIFormDataRequest.h"
    @implementation RootViewController
    int intButton;
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        self.title = @"Select Images";
        arrImages = [[NSMutableArray alloc]init];
    }
    - (IBAction)btnTakePicture_Clicked:(id)sender
    {
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Select Image from..." delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Camera", @"Image Gallary", nil];
        actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
        actionSheet.alpha=0.90;
        actionSheet.tag = 1;
        [actionSheet showInView:self.view];
        [actionSheet release];
        UIButton *btn = (UIButton *)sender;
        intButton = btn.tag;
    }
    - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
    {
        switch (actionSheet.tag)
        {
            case 1:
                switch (buttonIndex)
                {
                    case 0:
                    {
    #if TARGET_IPHONE_SIMULATOR
                        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"Camera not available." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                        [alert show];
                        [alert release];
    #elif TARGET_OS_IPHONE
                        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                        picker.delegate = self;
                        //picker.allowsEditing = YES;
                        [self presentModalViewController:picker animated:YES];
                        [picker release];
    #endif
                    }
                    break;
                    case 1:
                    {
                        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                        picker.delegate = self;
                        [self presentModalViewController:picker animated:YES];
                        [picker release];
                    }
                    break;
                }
                break;
                default:
                break;
        }
    }
    -(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
    {
        NSData *dataImage = UIImageJPEGRepresentation([info objectForKey:@"UIImagePickerControllerOriginalImage"],1);
        UIImage *img = [[UIImage alloc] initWithData:dataImage];
    
        if (intButton == 1) {
            [btnImage1 setBackgroundImage:img forState:UIControlStateNormal];
            [btnImage1 setImage:nil forState:UIControlStateNormal];
        } else if (intButton == 2) {
            [btnImage2 setBackgroundImage:img forState:UIControlStateNormal];
            [btnImage2 setImage:nil forState:UIControlStateNormal];
        } else if (intButton == 3) {
            [btnImage3 setBackgroundImage:img forState:UIControlStateNormal];
            [btnImage3 setImage:nil forState:UIControlStateNormal];
        } else {
            [btnImage4 setBackgroundImage:img forState:UIControlStateNormal];
            [btnImage4 setImage:nil forState:UIControlStateNormal];
        }
        [arrImages addObject:dataImage];
        [picker dismissModalViewControllerAnimated:YES];
    }
    - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
        [self.navigationController dismissModalViewControllerAnimated:YES];
    }
    - (IBAction)btnPostImages_Clicked:(id)sender {
    if ([arrImages count] > 0) {
        NSString *strURL = @"Write Your URL Here.";
        ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:strURL]];
        [request setDelegate:self];
        [request setPostValue:@"This is sample text..." forKey:@"text"];
        for (int i = 0; i < [arrImages count]; i++) {
            [request addData:[arrImages objectAtIndex:i] withFileName:@"image.jpg" andContentType:@"image/jpeg" forKey:[NSString stringWithFormat:@"image%d", i + 1]];
        }
        [request startAsynchronous];
    } else {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Message" message:@"Please select images..." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alertView show];
        [alertView release];
    }
    }
    - (void)requestFinished:(ASIHTTPRequest *)request {
        NSString *receivedString = [request responseString];
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Message" message:receivedString delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alertView show];
        [alertView release];
    }
    - (void)requestFailed:(ASIHTTPRequest *)request {
        NSString *receivedString = [request responseString];
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Message" message:receivedString delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alertView show];
        [alertView release];
    }