Archive for December, 2011

Objective-C Math functions


Math functions
double pow ( double, double ) – power of
NSLog(@”%.f”, pow(3,2) ); //result 9
NSLog(@”%.f”, pow(3,3) ); //result 27
double  sqrt( double ) – square root
NSLog(@”%.f”, sqrt(16) ); //result 4
NSLog(@”%.f”, sqrt(81) ); //result 9
double ceil ( double ) – if the argument has any decimal part, returns the next bigger integer
NSLog(@”res: %.f”, ceil(3.000000000001)); //result 4
NSLog(@”res: %.f”, ceil(3.00)); //result 3
double floor ( double ) – removes the decimal part of the argument
NSLog(@”res: %.f”, floor(3.000000000001)); //result 3
NSLog(@”res: %.f”, floor(3.9999999)); //result 3
double round ( double ) – rounds the argument
NSLog(@”res: %.f”, round(3.5)); //result 4
NSLog(@”res: %.f”, round(3.46)); //result 3
NSLog(@”res: %.f”, round(-3.5)); //NB: this one returns -4
double fmin ( double, double ) – returns the smaller argument
NSLog(@”res: %.f”, fmin(5,10)); //result 5
double fmax ( double, double ) – returns the bigger argument
NSLog(@”res: %.f”, fmax(5,10)); //result 10
double  fabs( double ) – returns the absolute value of the argument
NSLog(@”res: %.f”, fabs(10)); //result 10
NSLog(@”res: %.f”, fabs(-10)); //result 10
Eventually you will find also all the trigonometry you’ll need as: sin, cos, tan, atan, and their variations.
Few math constants
As found in the math.h
#define M_E         2.71828182845904523536028747135266250   /* e */
#define M_LOG2E     1.44269504088896340735992468100189214   /* log 2e */
#define M_LOG10E    0.434294481903251827651128918916605082  /* log 10e */
#define M_LN2       0.693147180559945309417232121458176568  /* log e2 */
#define M_LN10      2.30258509299404568401799145468436421   /* log e10 */
#define M_PI        3.14159265358979323846264338327950288   /* pi */
#define M_PI_2      1.57079632679489661923132169163975144   /* pi/2 */
#define M_PI_4      0.785398163397448309615660845819875721  /* pi/4 */
#define M_1_PI      0.318309886183790671537767526745028724  /* 1/pi */
#define M_2_PI      0.636619772367581343075535053490057448  /* 2/pi */
#define M_2_SQRTPI  1.12837916709551257389615890312154517   /* 2/sqrt(pi) */
#define M_SQRT2     1.41421356237309504880168872420969808   /* sqrt(2) */
#define M_SQRT1_2   0.707106781186547524400844362104849039  /* 1/sqrt(2) */

#define    MAXFLOAT    ((float)3.40282346638528860e+38)

Leave a comment

Send NSString to windows Web Service through SOAP


– (void) Send :(NSString*) tarXML
{
    recordResults = FALSE;
    
    NSString *soapMessage = [NSString stringWithFormat:
                             @”<?xml version=”1.0″ encoding=”utf-8″?>n”
                             “<soap:Envelope xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xmlns:xsd=”http://www.w3.org/2001/XMLSchema&#8221; xmlns:soap=”http://schemas.xmlsoap.org/soap/envelope/”>n&#8221;
                             “<soap:Body>n”
                             “<TestDecrypt xmlns=”http://tempuri.org/”>n&#8221;
                             “<tarData>%@</tarData>n”
                             “</TestDecrypt>n”
                             “</soap:Body>n”
                             “</soap:Envelope>n”, tarXML
                             ];
    NSLog(soapMessage);
    
    NSURL *url = [NSURL URLWithString:@”http://sergeynotebook/WebService1/Service1.asmx”%5D;
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
    NSString *msgLength = [NSString stringWithFormat:@”%d”, [soapMessage length]];
    
    [theRequest addValue: @”text/xml; charset=utf-8″ forHTTPHeaderField:@”Content-Type”];
    [theRequest addValue: @”http://tempuri.org/TestDecrypt&#8221; forHTTPHeaderField:@”SOAPAction”];
    [theRequest addValue: msgLength forHTTPHeaderField:@”Content-Length”];
    [theRequest setHTTPMethod:@”POST”];
    [theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    
    if( theConnection )
    {
        webData = [[NSMutableData data] retain];
    }
    else
    {
        NSLog(@”theConnection is NULL”);
    }
    
}
 
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@”ERROR with theConenction”);
    [connection release];
    [webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@”DONE. Received Bytes: %d”, [webData length]);
    NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
    NSLog(theXML);
    [theXML release];
    
    
    [connection release];
    [webData release];
}

Leave a comment

Generate an random Numbur in Xode


-(int)randomInRange:(NSRange)range except:(NSArray*)exceptionArray{
    int r ;
    BOOL isSame = TRUE;
    
    while (isSame) {
        isSame = FALSE;
        r = rand() % range.length + range.location;
        for (NSNumber *number in exceptionArray) {
            if([number intValue] == r){
                isSame = TRUE;
                break;
            }
        }
    }
    
    return r;
}
 
//
 
[self randomInRange:NSMakeRange(1, 10) except:[NSArray arrayWithObjects:[NSNumber numberWithInt:2],[NSNumber numberWithInt:1], nil]];

Leave a comment

Removing duplicates in an NSMutableArray


for (i=0; i < [mutArray count]; i++ ) {
      for (j=(i+1); j < [mutArray count]; j++) {
          if ([[mutArray objectAtIndex:i] isEqualTo:[mutArray
objectAtIndex:j]]) {
            [mutArray removeObjectAtIndex:j];
            j–; // everything shifts down, so at j there is now an
entry we haven’t yet checked
          }
      }
}

Leave a comment

ios developer interview questions


Q)What is iPhone?
IPhone is a combination of internet and multimedia enabled smart phone developed by Apple Inc

Q)What are the features of iphone 3gs?
Video: Videos can be edited, shared. High quality VGA video can be shot in portrait or landscape

Q)What is iphone OS?
iPhone OS runs on iPhone and iPod touch devices. Hardware devices are managed by iPhone OS and provides the technologies needed for implementing native applications on the phone

Q)What is iphone sdk?
iPhone SDK is available with tools and interfaces needed for developing, installing and running custom native applications

Q)What is iphone architecture?
It is similar to MacOS X architecture. It acts as an intermediary between the iPhone and iPod hardware an the appearing applications on the screen

Q)What is iphone reference library?
iPhone reference library is a set of reference documents for iPhone OS. It can be downloaded by subscribing to the iPhone OS Library doc set

Q)What are sensors in iphone?
The proximity sensor immediately turns off the display when the iPhone is lifted to ear. With this sensor the power is saved and accidental dialing is prevented

Q)What are the location services?
Applications such as Maps, camera and compass are allowed to use the information from cellular, Wi-Fi and Global Positioning System…………..

Leave a comment

Hide back button


[self.navigationItem setHidesBackButton:YES];

Leave a comment

Send file (images) to web server using POST method


//This example send email with attachment using server side
//So iPhone will fill form and send proper request to web server using POST method
//For test you can use attached sendEmail.php

-(NSMutableData *)generateDataFromText:(NSString *)dataText fieldName:(NSString *)fieldName{
NSString *post = [NSString stringWithFormat:@”–AaB03xrnContent-Disposition: form-data; name=”%@”rnrn”, fieldName];
// Get the post header int ASCII format:
NSData *postHeaderData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

// Generate the mutable data variable:
NSMutableData *postData = [[NSMutableData alloc] initWithLength:[postHeaderData length] ];
[postData setData:postHeaderData];

NSData *uploadData = [dataText dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

// Add the text:
[postData appendData: uploadData];

// Add the closing boundry:
[postData appendData: [@”rn” dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];

// Return the post data:
return postData;
}

– (NSData *)generatePostDataForData:(NSData *)uploadData fileName:(NSString *)fileName
{
// Generate the post header:

NSString *post = [NSString stringWithFormat:@”–AaB03xrnContent-Disposition: form-data; name=”attachment”; filename=”%@”rnContent-Type: video/3gpprnrn”, fileName];

// Get the post header int ASCII format:
NSData *postHeaderData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

// Generate the mutable data variable:
NSMutableData *postData = [[NSMutableData alloc] initWithLength:[postHeaderData length] ];
[postData setData:postHeaderData];

// Add the image:
[postData appendData: uploadData];

// Add the closing boundry:
[postData appendData: [@”rn–AaB03x–” dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];

// Return the post data:
return postData;
}

-(void)sendEmailTo:(NSString *)email name:(NSString *)name {

NSString *emailBody = @”Just some HTML text”

//Fill some text fields
NSMutableData *postData = [self generateDataFromText:email fieldName:@”to_email”];
[postData appendData:[self generateDataFromText:@”10000000″ fieldName:@”MAX_FILE_SIZE”]];
[postData appendData:[self generateDataFromText:name fieldName:@”to_name”]];
[postData appendData:[self generateDataFromText:email fieldName:@”to_email”]];
[postData appendData:[self generateDataFromText:[[NSUserDefaults standardUserDefaults] stringForKey:@”name_preference”] fieldName:@”from_name”]];
[postData appendData:[self generateDataFromText:[[NSUserDefaults standardUserDefaults] stringForKey:@”email_preference”] fieldName:@”from_email”]];
[postData appendData:[self generateDataFromText:currentEmail.emailSubject fieldName:@”subject”]];
[postData appendData:[self generateDataFromText:emailBody fieldName:@”body”]];
[postData appendData:[self generateDataFromText:email fieldName:@”to_email”]];

//Prepare data for file
NSData *dataObj = [NSData dataWithContentsOfFile:@”/link/to/file”];
[postData appendData:[self generatePostDataForData:dataObj fileName:@”fileName”]];

// Setup the request:
NSMutableURLRequest *uploadRequest = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:kLinkToPostFile] cachePolicy: NSURLRequestReloadIgnoringLocalCacheData timeoutInterval: 30 ] autorelease];
[uploadRequest setHTTPMethod:@”POST”];
[uploadRequest setValue:[NSString stringWithFormat:@”%d”, [postData length]] forHTTPHeaderField:@”Content-Length”];
[uploadRequest setValue:@”multipart/form-data; boundary=AaB03x” forHTTPHeaderField:@”Content-Type”];
[uploadRequest setHTTPBody: postData];

NSData *responseData = [NSURLConnection sendSynchronousRequest:uploadRequest returningResponse:nil error:nil];
NSLog([[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding]);

}

Leave a comment

Get IP address of iPhone


/*
*  IPAdress.h
*
*
*/

#define MAXADDRS    32

extern char *if_names[MAXADDRS];
extern char *ip_names[MAXADDRS];
extern char *hw_addrs[MAXADDRS];
extern unsigned long ip_addrs[MAXADDRS];

// Function prototypes

void InitAddresses();
void FreeAddresses();
void GetIPAddresses();
void GetHWAddresses();

/*
*  IPAddress.c
*
*/

#include “IPAddress.h”

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/sockio.h>
#include <net/if.h>
#include <errno.h>
#include <net/if_dl.h>

#include “IPAddress.h”

#define    min(a,b)    ((a) < (b) ? (a) : (b))
#define    max(a,b)    ((a) > (b) ? (a) : (b))

#define BUFFERSIZE    4000

char *if_names[MAXADDRS];
char *ip_names[MAXADDRS];
char *hw_addrs[MAXADDRS];
unsigned long ip_addrs[MAXADDRS];

static int   nextAddr = 0;

void InitAddresses()
{
int i;
for (i=0; i<MAXADDRS; ++i)
{
if_names[i] = ip_names[i] = hw_addrs[i] = NULL;
ip_addrs[i] = 0;
}
}

void FreeAddresses()
{
int i;
for (i=0; i<MAXADDRS; ++i)
{
if (if_names[i] != 0) free(if_names[i]);
if (ip_names[i] != 0) free(ip_names[i]);
if (hw_addrs[i] != 0) free(hw_addrs[i]);
ip_addrs[i] = 0;
}
InitAddresses();
}

void GetIPAddresses()
{
int                 i, len, flags;
char                buffer[BUFFERSIZE], *ptr, lastname[IFNAMSIZ], *cptr;
struct ifconf       ifc;
struct ifreq        *ifr, ifrcopy;
struct sockaddr_in    *sin;

char temp[80];

int sockfd;

for (i=0; i<MAXADDRS; ++i)
{
if_names[i] = ip_names[i] = NULL;
ip_addrs[i] = 0;
}

sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0)
{
perror(“socket failed”);
return;
}

ifc.ifc_len = BUFFERSIZE;
ifc.ifc_buf = buffer;

if (ioctl(sockfd, SIOCGIFCONF, &ifc) < 0)
{
perror(“ioctl error”);
return;
}

lastname[0] = 0;

for (ptr = buffer; ptr < buffer + ifc.ifc_len; )
{
ifr = (struct ifreq *)ptr;
len = max(sizeof(struct sockaddr), ifr->ifr_addr.sa_len);
ptr += sizeof(ifr->ifr_name) + len;    // for next one in buffer

if (ifr->ifr_addr.sa_family != AF_INET)
{
continue;    // ignore if not desired address family
}

if ((cptr = (char *)strchr(ifr->ifr_name, ‘:’)) != NULL)
{
*cptr = 0;        // replace colon will null
}

if (strncmp(lastname, ifr->ifr_name, IFNAMSIZ) == 0)
{
continue;    /* already processed this interface */
}

memcpy(lastname, ifr->ifr_name, IFNAMSIZ);

ifrcopy = *ifr;
ioctl(sockfd, SIOCGIFFLAGS, &ifrcopy);
flags = ifrcopy.ifr_flags;
if ((flags & IFF_UP) == 0)
{
continue;    // ignore if interface not up
}

if_names[nextAddr] = (char *)malloc(strlen(ifr->ifr_name)+1);
if (if_names[nextAddr] == NULL)
{
return;
}
strcpy(if_names[nextAddr], ifr->ifr_name);

sin = (struct sockaddr_in *)&ifr->ifr_addr;
strcpy(temp, inet_ntoa(sin->sin_addr));

ip_names[nextAddr] = (char *)malloc(strlen(temp)+1);
if (ip_names[nextAddr] == NULL)
{
return;
}
strcpy(ip_names[nextAddr], temp);

ip_addrs[nextAddr] = sin->sin_addr.s_addr;

++nextAddr;
}

close(sockfd);
}

void GetHWAddresses()
{
struct ifconf ifc;
struct ifreq *ifr;
int i, sockfd;
char buffer[BUFFERSIZE], *cp, *cplim;
char temp[80];

for (i=0; i<MAXADDRS; ++i)
{
hw_addrs[i] = NULL;
}

sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0)
{
perror(“socket failed”);
return;
}

ifc.ifc_len = BUFFERSIZE;
ifc.ifc_buf = buffer;

if (ioctl(sockfd, SIOCGIFCONF, (char *)&ifc) < 0)
{
perror(“ioctl error”);
close(sockfd);
return;
}

ifr = ifc.ifc_req;

cplim = buffer + ifc.ifc_len;

for (cp=buffer; cp < cplim; )
{
ifr = (struct ifreq *)cp;
if (ifr->ifr_addr.sa_family == AF_LINK)
{
struct sockaddr_dl *sdl = (struct sockaddr_dl *)&ifr->ifr_addr;
int a,b,c,d,e,f;
int i;

strcpy(temp, (char *)ether_ntoa(LLADDR(sdl)));
sscanf(temp, “%x:%x:%x:%x:%x:%x”, &a, &b, &c, &d, &e, &f);
sprintf(temp, “%02X:%02X:%02X:%02X:%02X:%02X”,a,b,c,d,e,f);

for (i=0; i<MAXADDRS; ++i)
{
if ((if_names[i] != NULL) && (strcmp(ifr->ifr_name, if_names[i]) == 0))
{
if (hw_addrs[i] == NULL)
{
hw_addrs[i] = (char *)malloc(strlen(temp)+1);
strcpy(hw_addrs[i], temp);
break;
}
}
}
}
cp += sizeof(ifr->ifr_name) + max(sizeof(ifr->ifr_addr), ifr->ifr_addr.sa_len);
}

close(sockfd);
}

//Somewhere in your code
– (NSString *)deviceIPAdress {
InitAddresses();
GetIPAddresses();
GetHWAddresses();
return [NSString stringWithFormat:@”%s”, ip_names[1]];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
– (void)viewDidLoad {
[super viewDidLoad];
ipAddress.text = [self deviceIPAdress];
}

Leave a comment

Get pixel information from UIImage


UIImage *uiImage = [UIImage imageNamed:@”myimage.png”];

CGImageRef image = uiImage.CGImage;
NSUInteger width = CGImageGetWidth(image);
NSUInteger height = CGImageGetHeight(image);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
UInt8 * rawData = malloc(height * width * 4);

int bytesPerPixel = 4;
int bytesPerRow = bytesPerPixel * width;

NSUInteger bitsPerComponent = 8;
CGContextRef context1 = CGBitmapContextCreate(
rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big
);
CGColorSpaceRelease(colorSpace);

CGContextDrawImage(context1, CGRectMake(0, 0, width, height), image);
CGContextRelease(context1);

//Now to get byte for ppixel you need to call
//rawData[x * bytesPerRow  + y * bytesPerPixel]

Leave a comment

Connect to Evernote


#import “THTTPClient.h”
#import “TBinaryProtocol.h”
#import “UserStore.h”
#import “NoteStore.h”

– (void)Test
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// Keep this key private
NSString *consumerKey = [[[NSString alloc]
initWithString: @”YOUR_CONSUMER_KEY_HERE” ] autorelease];
NSString *consumerSecret = [[[NSString alloc]
initWithString: @”YOUR_CONSUMER_SECRET_HERE”] autorelease];
// For testing we use the sandbox server.
NSURL *userStoreUri = [[[NSURL alloc]
initWithString: @”https://sandbox.evernote.com/edam/user”%5D autorelease];
NSString *noteStoreUriBase = [[[NSString alloc]
initWithString: @”http://sandbox.evernote.com/edam/note/”%5D autorelease];
// These are for test purposes. At some point the user will provide his/her own.
NSString *username = [[[NSString alloc]
initWithString: @”YOUR_USERNAME_HERE”] autorelease];
NSString *password = [[[NSString alloc]
initWithString: @”YOUR_PASSWORD_HERE”] autorelease];

THTTPClient *userStoreHttpClient = [[[THTTPClient alloc]
initWithURL:userStoreUri] autorelease];
TBinaryProtocol *userStoreProtocol = [[[TBinaryProtocol alloc]
initWithTransport:userStoreHttpClient] autorelease];
EDAMUserStoreClient *userStore = [[[EDAMUserStoreClient alloc]
initWithProtocol:userStoreProtocol] autorelease];
EDAMNotebook* defaultNotebook = NULL;

BOOL versionOk = [userStore checkVersion:@”Cocoa EDAMTest” :
[EDAMUserStoreConstants EDAM_VERSION_MAJOR] :
[EDAMUserStoreConstants EDAM_VERSION_MINOR]];

if (versionOk == YES)
{
EDAMAuthenticationResult* authResult =
[userStore authenticate:username :password
:consumerKey :consumerSecret];
EDAMUser *user = [authResult user];
NSString *authToken = [authResult authenticationToken];
NSLog(@”Authentication was successful for: %@”, [user username]);
NSLog(@”Authentication token: %@”, authToken);

NSURL *noteStoreUri =  [[[NSURL alloc]
initWithString:[NSString stringWithFormat:@”%@%@”,
noteStoreUriBase, [user shardId]] ]autorelease];
THTTPClient *noteStoreHttpClient = [[[THTTPClient alloc]
initWithURL:noteStoreUri] autorelease];
TBinaryProtocol *noteStoreProtocol = [[[TBinaryProtocol alloc]
initWithTransport:noteStoreHttpClient] autorelease];
EDAMNoteStoreClient *noteStore = [[[EDAMNoteStoreClient alloc]
initWithProtocol:noteStoreProtocol] autorelease];

NSArray *notebooks = [[noteStore listNotebooks:authToken] autorelease];
NSLog(@”Found %d notebooks”, [notebooks count]);
for (int i = 0; i < [notebooks count]; i++)
{
EDAMNotebook* notebook = (EDAMNotebook*)[notebooks objectAtIndex:i];
if ([notebook defaultNotebook] == YES)
{
defaultNotebook = notebook;
}
NSLog(@” * %@”, [notebook name]);
}

NSLog(@”Creating a new note in default notebook: %@”, [defaultNotebook name]);

// Skipping the image resource section…

EDAMNote *note = [[[EDAMNote alloc] init] autorelease];
[note setNotebookGuid:[defaultNotebook guid]];
[note setTitle:@”Test note from Cocoa Test.”];
NSMutableString* contentString = [[[NSMutableString alloc] init] autorelease];
[contentString setString:    @”<?xml version=”1.0″ encoding=”UTF-8″?>”];
[contentString appendString:@”<!DOCTYPE en-note SYSTEM “http://xml.evernote.com/pub/enml.dtd”>”%5D;
[contentString appendString:@”            <en-note>Here is the Olive Tree Test note.<br/>”];
[contentString appendString:@”            </en-note>”];
[note setContent:contentString];
[note setCreated:(long long)[[NSDate date] timeIntervalSince1970] * 1000];
EDAMNote *createdNote = [noteStore createNote:authToken :note];
if (createdNote != NULL)
{
NSLog(@”Created note: %@”, [createdNote title]);
}
}

[pool drain];
}

Leave a comment