Translate

Tuesday, May 29, 2012

how to get device mac address?

.h file

#import <sys/socket.h>
#import <sys/sysctl.h>
#import <net/if.h>
#import <net/if_dl.h>

+(NSString*)getMacAddress;

.m file


+ (NSString *)getMacAddress
{
    int                 mgmtInfoBase[6];
    char                *msgBuffer = NULL;
    size_t              length;
    unsigned char       macAddress[6];
    struct if_msghdr    *interfaceMsgStruct;
    struct sockaddr_dl  *socketStruct;
    NSString            *errorFlag = NULL;
   
    // Setup the management Information Base (mib)
    mgmtInfoBase[0] = CTL_NET;        // Request network subsystem
    mgmtInfoBase[1] = AF_ROUTE;       // Routing table info
    mgmtInfoBase[2] = 0;             
    mgmtInfoBase[3] = AF_LINK;        // Request link layer information
    mgmtInfoBase[4] = NET_RT_IFLIST;  // Request all configured interfaces
   
    // With all configured interfaces requested, get handle index
    if ((mgmtInfoBase[5] = if_nametoindex("en0")) == 0)
        errorFlag = @"if_nametoindex failure";
    else
    {
        // Get the size of the data available (store in len)
        if (sysctl(mgmtInfoBase, 6, NULL, &length, NULL, 0) < 0)
            errorFlag = @"sysctl mgmtInfoBase failure";
        else
        {
            // Alloc memory based on above call
            if ((msgBuffer = malloc(length)) == NULL)
                errorFlag = @"buffer allocation failure";
            else
            {
                // Get system information, store in buffer
                if (sysctl(mgmtInfoBase, 6, msgBuffer, &length, NULL, 0) < 0)
                    errorFlag = @"sysctl msgBuffer failure";
            }
        }
    }
    // Befor going any further...
    if (errorFlag != NULL)
    {
        NSLog(@"Error: %@", errorFlag);
        return errorFlag;
    }
    // Map msgbuffer to interface message structure
    interfaceMsgStruct = (struct if_msghdr *) msgBuffer;
    // Map to link-level socket structure
    socketStruct = (struct sockaddr_dl *) (interfaceMsgStruct + 1); 
    // Copy link layer address data in socket structure to an array
    memcpy(&macAddress, socketStruct->sdl_data + socketStruct->sdl_nlen, 6); 
    // Read from char array into a string object, into traditional Mac address format
    NSString *macAddressString = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",
                                  macAddress[0], macAddress[1], macAddress[2],
                                  macAddress[3], macAddress[4], macAddress[5]];
    NSLog(@"Mac Address: %@", macAddressString); 
    // Release the buffer memory
    free(msgBuffer);
    return macAddressString;
}

or if viewcontroller

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [ViewController getMacAddress];
}

How to get device name?

device name

.h file

#include <sys/utsname.h>

+(NSString*)deviceName;

.m file

+(NSString*)deviceName
{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString* platform =  [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
   
    NSString *deviceName;
   
    if ([platform isEqualToString:@"iPad1,1"])  
    {
        deviceName = @"iPad(WiFi)";
    }
    else if ([platform isEqual:@"iPad1,2"])
    {
        deviceName = @"iPad3G";
    }
    else if ([platform isEqualToString:@"iPad2,1"])
    {
        deviceName = @"iPad2(WiFi)";
    }
    else if ([platform isEqualToString:@"iPad2,2"])
    {
        deviceName = @"iPad2(GSM)";
    }
    else if ([platform isEqualToString:@"iPad2,3"])
    {
        deviceName = @"iPad2(CDMA)";
    }
    else if ([platform isEqualToString:@"iPad2,4"])
    {
        deviceName = @"iPad2";
    }
    else if ([platform isEqualToString:@"iPad3,1"])
    {
        deviceName = @"iPad3G(WiFi)";
    }
    else if ([platform isEqualToString:@"iPad3,2"])
    {
        deviceName = @"iPad3G(4G)";
    }
    else if ([platform isEqualToString:@"iPad3,3"])
    {
        deviceName = @"iPad3G(4G)";
    }
    else if ([platform isEqualToString:@"iPhone1,1"])
    {
        deviceName = @"iPhone1G";
    }
    else if ([platform isEqualToString:@"iPhone1,2"])
    {
        deviceName = @"iPhone3G";
    }
    else if ([platform isEqualToString:@"iPhone2,1"])
    {
        deviceName = @"iPhone3GS";
    }
    else if ([platform isEqualToString:@"iPhone3,1"] || [platform isEqual:@"iPhone3,2"] || [platform isEqual:@"iPhone3,3"])
    {
        deviceName = @"iPhone4";
    }
    else if ([platform isEqualToString:@"iPhone3,3"])
    {
        deviceName = @"VerizoniPhone 4";
    }
    else if ([platform isEqualToString:@"iPhone4,1"])
    {
        deviceName = @"iPhone4S";
    }
    else if ([platform isEqualToString:@"iPod1,1"])
    {
        deviceName = @"iPod1stGen";
    }
    else if ([platform isEqualToString:@"iPod2,1"])
    {
        deviceName = @"iPod2ndGen";
    }
    else if ([platform isEqualToString:@"iPod3,1"])
    {
        deviceName = @"iPod3rdGen";
    }
    else if ([platform isEqualToString:@"iPod4,1"])
    {
        deviceName = @"iPod4thGen";
    }
    else if ([platform isEqualToString:@"x86_64"] || [platform isEqualToString:@"i386"])
    {
        deviceName = @"Simulator";
    }
    return deviceName;
}


or  if viewcontroller

- (void)viewDidLoad
{
    [super viewDidLoad];
     
    [ViewController deviceName];
}








Thursday, May 24, 2012

Using The Twitter Framework in iOS 5

Using The Twitter Framework in iOS 5

The twitter framework apple has added is a Christmas gift to all the iOS developers as twitter integration has now become a child's play. By using the twitter framework you may now post your stuff to twitter but a user only have to connect to Twitter with his account once and he/she can do this in the setting section of the iPhone or iPod and look for the twitter app settings. After that, apps have the possibility to post a tweet with the users account.

TWTweetComposeViewController class  in the twitter framework makes every thing possible if you want to tweet in the iOS 5 but if you want the twitter integration in the other devices then in that case you have to use the old methods of tweeting and in case if your application has support from iOS 4 to iOS 5 then in that case you need to perform a check and then tweet happily ever after . 

In this tutorial I’m going to show you how to use this class and start using the Twitter integration. You will be surprised how easy this class is to implement. Check the end of this article for a sample project you can download.


Step 1: Open Xcode and create an empty project add the ViewController subclass file in the project with Xib and create a view which looks something like the one given below.




Step 2: Select the .h file of your viewcontroller and create a functions to connect to the button, an IBOutlet to connect to the text field and one alert view object which will be used to notify the user regarding his tweets. Also add the twitter framework into your project, select the xcode project file and go to build phases and from their expand the link binary with library option.




Link Binary with library




Twitter Framework




 Given below is the code view for the .h file of the view controller



Step3: Select the .m file of your view controller and add the below code, i have divided the code blocks with the explanation for the same so that it will be easy for you to understand.

Code explanation: a) First we are checking whether the device supports the Twitter framework or not.






or you can also check for twitter account with the help of below code





b) Secondly we set the text for the content that we want to tweet with the help of the method setInitialText and then display the twitter composer modal view controller.





c) A user has to know whether his tweet has been posted or not so we will also check this with the help of TWTweetComposerViewControllerResult type and with the help of completionHandler property.
completionHandler: This is the handler that gets called when the user is done composing the tweet.

TWTweetComposerViewControllerResult: This is a enumerator with various values that determines whether a tweet is done successfully or has failed due to some problems like no internet connection or 3G connections etc.





Step 4: Once all the above code is understood by you and everything is working fine so far then its time you connected your IBOutlets and IBAction and then move to the AppDelegate.m file where you will add the twitter view into the iPhone window in the application did finish launching method.



Step 5: Run the application and start tweeting.





In case if their are no twitter account configured in your simulator you will get the below screen







download link :  https://github.com/downloads/KRadix/CommonUtility/TwitterFrameworkDemo.zip

Wednesday, May 23, 2012

How to take a screenshot programmatically

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

UPDATE April 2011: for retina display, change the first line into this:
 
 
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
    UIGraphicsBeginImageContextWithOptions(self.window.bounds.size, NO, [UIScreen mainScreen].scale);
else
    UIGraphicsBeginImageContext(self.window.bounds.size);
 

NSXML Parser

book.xml

<?xml version="1.0" encoding="UTF-8"?>
<data>

<books>
    <book>
        <bookid>1</bookid>
        <title><![CDATA[Book 1]]></title>
        <authors><![CDATA[Author 1]]></authors>
        <imageURL><![CDATA[image1.png]]></imageURL>
        <webURL><![CDATA[http://www.google.com]]></webURL>
</book>
    <book>
        <bookid>2</bookid>
        <title><![CDATA[Book 2]]></title>
        <authors><![CDATA[Author 2]]></authors>
        <imageURL><![CDATA[image2.png]]></imageURL>
        <webURL><![CDATA[http://www.google.com]]></webURL>
    </book>
   
</data>


.h File


#import <UIKit/UIKit.h>

@interface NSXMLParserViewController : UIViewController<NSXMLParserDelegate>
{
  NSMutableString *tagValue;
  NSMutableArray *tagArray;
    NSString *tagName;
}

@end


.m File

#import "NSXMLParser.h"

@implementation NSXMLParser

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    tagArray=[[NSMutableArray alloc]init];
   
    tagName=[[NSString alloc]initWithString:@""];
   
   NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:[NSData dataWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"book.xml"]]];
   
    [xmlParser setDelegate:self];
    [xmlParser parse];
   
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
    attributes:(NSDictionary *)attributeDict {
   
   
    if([elementName isEqualToString:@"title"]||[elementName isEqualToString:@"imageURL"]||[elementName isEqualToString:@"webURL"]||[elementName isEqualToString:@"bookid"]||[elementName isEqualToString:@"authors"]){
   
   // if([elementName isEqualToString:@"title"]||[elementName isEqualToString:@"maincat"]||[elementName isEqualToString:@"subcat"]||[elementName isEqualToString:@"author"]){
       
        tagValue=[[NSMutableString alloc]init];
       

    }
   
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    [tagValue appendString:string];
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
   
    NSString *string;
   
    if([elementName isEqualToString:@"title"]){
        string=[tagValue stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        NSLog(@"title %@",string);
        [tagArray addObject:string];
    }
   else if([elementName isEqualToString:@"imageURL"]){
        string=[tagValue stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
       NSLog(@"imageURL %@",string);
        [tagArray addObject:string];
    }
    else if([elementName isEqualToString:@"webURL"]){
        string=[tagValue stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        NSLog(@"webURL %@",string);
        [tagArray addObject:string];
    }
    else if([elementName isEqualToString:@"authors"]){
        string=[tagValue stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        NSLog(@"author %@",string);
        [tagArray addObject:string];
    }
    else if([elementName isEqualToString:@"bookid"]){
        string=[tagValue stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        NSLog(@"bookid %@",string);
        [tagArray addObject:string];
    }
}