Monday, November 16, 2015

OpenSSL Library with iOS 4.2

Create OpenSSL Libary:
  • Download OpenSSL Sourcecode
  • Build OpenSSL for i368 iPhoneSimulator:
    • cd openssl-1.0.0c
      mkdir openssl_arm
      mkdir openssl_i386
      ./config --openssldir=/Users/<username>/openssl-1.0.0c/openssl_i386
    • Edit Makefile:
      • Change CC = cc to:
        CC= /Developer/usr/bin/gcc-4.2
      • Add as first item to CFLAG:
        -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.2.sdk
    • Change in crypto/ui/ui_openssl.c
      static volatile sig_atomic_t intr_signal;
      to
      static volatile int intr_signal;
      for preventing building error
    • Build it:
      make
      make install
    • Your libcrypto.a and libssl.a are in the folder openssl_i368/lib
    • Rename the two files to libcrypto_i386.a and libssl_i386.a
  • Build OpenSSL for arm iPhoneOS:
    • mv openssl_i386 openssl_i386_lib
      make clean
    • Edit Makefile:
      • Search and replace openssl_i386 with openssl_arm
      • Change -arch i386 in CFLAG to:
        -arch armv6
      • Change
        CC=  /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/gcc-4.2
        to
        CC=  /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc-4.2
      • Change
        -isysroot  /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.2.sdk
        to
        -isysroot  /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.2.sdk
    • Build it:
      make
      make install
    • Your libcrypto.a and libssl.a are in the folder openssl_armv6/lib
    • Rename the two files to libcrypto_armv6.a and libssl_armv6.a

  • Build OpenSSL for armv7 iPhoneOS:
    • mv openssl_armv6 openssl_armv6_lib
      make clean
    • Edit Makefile:
      • Search and replace openssl_armv6 with openssl_armv7
      • Change -arch armv6 in CFLAG to:
        -arch armv7
    • Build it:
      make
      make install
    • Your libcrypto.a and libssl.a are in the folder openssl_armv7/lib
    • Rename the two files to libcrypto_armv7.a and libssl_armv7.a

Tuesday, June 1, 2010

Linker Issue" for class reference.

Hi all,

I have seen a lot of issues in different forums regarding "Linker Issue" for class reference.

Firstly try to show target in navigator and check whether any file is unchecked like in Fig 1

Fig 1

If there is any file being unchecked then it will show an error as in Fig 1.

".objc_class_name_SecondLinkerViewController", referenced from :

Literal-pointer@__OBJC@__cls_refs@SecondLinkerViewController in LinkerViewController.o
Symbol(s) not found
Collect2 : Id returned 1 exit


To resolve this issue, we are required to check the target checkmark icon, as in Fig 2



After checking these files, and build again, this issue will get resolved.

Thanks.


Friday, May 28, 2010

How to read binary data from file system

Good evening every one,

Today I have created one small code where I am trying to read and write the data in the binary format, so as to create the utility class for file management.

In this utility class, I am saving all the data in byte format, so that the end user if wants to write the encrypted data also, then he can encrypt and decrypt the data format at his end, and reading * writing of the data in file system should not get affected.

Here is the small example I am sharing regarding writing the binary data and reading it in collection format.

The utility class which I have created is named "FileManagerUtil.h,.m".

So in FileManagerUtil.h file I have created 5 methods,

-
(NSMutableData*) readDataForFile:(NSString*)fileName_;
- (BOOL) writeData:(id)data_ toFile:(NSString*)fileName_;


- (NSString *)removeTempDirectory;

- (NSString *)tempDirectoryPath:(NSString*)fileName_;

- (NSString *)applicationDocumentsDirectory;


and in FileManager.m file I have defined these methods as

1)

- (NSMutableData*) readDataForFile:(NSString*)fileName_ {
// check whether the document directory is available or not

NSString *documentsDirectoryPath = [self performSelector:@selector(tempDirectoryPath:) withObject:fileName_];


if ([[NSFileManager defaultManager] isReadableFileAtPath:documentsDirectoryPath]) {
NSMutableData *data_ = [NSMutableData dataWithContentsOfFile:documentsDirectoryPath];

return data_;
}

return nil;

}


2)

- (BOOL) writeData:(id)data_ toFile:(NSString*)fileName_ {
// check whether the document directory is available or not

NSString *documentsDirectoryPath = [self performSelector:@selector(tempDirectoryPath:) withObject:fileName_];
debug(@"%@",documentsDirectoryPath);

if ([[NSFileManager defaultManager] isWritableFileAtPath:documentsDirectoryPath]) {
NSLog(@"%@",data_);
[data_ writeToFile:documentsDirectoryPath atomically:YES];
return YES;
}

return NO;
}


3)

/**
Returns the path to the application's temp directory path.
*/

- (NSString *)removeTempDirectory {

NSString *tempDirPath = [[self performSelector:@selector(applicationDocumentsDirectory)] stringByAppendingPathComponent:@"temp"];

[[NSFileManager defaultManager] removeItemAtPath:tempDirPath error:nil];

return tempDirPath;
}



4)
/**
Returns the path to the application's temp directory path.
*/

- (NSString *)tempDirectoryPath:(NSString*)fileName_ {

NSString *tempDirPath = [[self performSelector:@selector(applicationDocumentsDirectory)] stringByAppendingPathComponent:@"temp"];

BOOL isDir = NO;
if (![[NSFileManager defaultManager] fileExistsAtPath:tempDirPath isDirectory: &isDir]) {
[[NSFileManager defaultManager] createDirectoryAtPath:tempDirPath attributes: nil];
}
if (!isDir) {
[[NSFileManager defaultManager] removeItemAtPath:tempDirPath error:nil];
[[NSFileManager defaultManager] createDirectoryAtPath:tempDirPath attributes:nil];
}

NSString *tempFilePath = [tempDirPath stringByAppendingPathComponent:fileName_];

if(![[NSFileManager defaultManager] isWritableFileAtPath:tempFilePath]){
[[NSFileManager defaultManager] createFileAtPath:tempFilePath contents:nil attributes: nil];
}
return tempFilePath;
}


5)

/**
Returns the path to the application's documents directory.
*/

- (NSString *)applicationDocumentsDirectory {

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}


Now, when I have to read the data from the file system for collections(like NSArray or NSDictionary),I am going to use NSPropertyListSerialization.

FileManagerUtil *fileManagerUtil = [[FileManagerUtil alloc] init];
NSMutableData *binaryData = [fileManagerUtil readDataForFile:@"filename.extension"];
NSString *error;

// If were to use mutabilityOption:NSPropertyListImmutable,
// we would get a run time error when trying to insert another volume

NSPropertyListFormat format;

id cacheData =[NSPropertyListSerialization propertyListFromData:binaryData
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:&format
errorDescription:&error];

Now check the type of cache data for collection

if([[cacheData class] isKindOfClass:[NSMutableDictionary class]]){
NSMutableDictionary *dictionary = (NSMutableDictionary*)cacheData;
}
else
if([[cacheData class] isKindOfClass:[NSMutableArray class]]){
NSMutableArray *dictionary = (NSMutableArray*)cacheData;
}



So in this way, if we want to secure our data in file system, we can do encryption of data before writing into file system and then decrypt it and then do its type parsing.

Thanks

For any quiries, please send me the mail, or put in the comments.

Wednesday, December 30, 2009

Clang Static Analyzer for iPhone Programming


Scan Analyzer : Clang Analyzer LLVM Compiler


Overview:


While we may be familiar with using tools likes Instruments to find and fix memory leaks in our application, the Clang Static Analyzer takes a different approach to memory leak detection by compiling our Xcode project and scanning each method, class, loop and logic block for potential leaks.

We may heard of Clang Static Analyzer referred to by the name of command line tool used to run the analyzer:scan-build.


Requirements


Download the Clang/LLVM Static Analyzer from http://clang-analyzer.llvm.org/ and click the link for checker-NNN.tar.bz2 (Latest build (Universal binary, 10.5+): checker-230.tar.bz2 (built December 8, 2009) ).



Installation


1) We are going to install the check-NNN binary in Mac /usr/local/bin folder. Run the following command to verify that this folder exists:

sudo mkdir -p /usr/local/bin


2) Open Terminal.app from the Application folders, and move the contents of checker-NNN to the usr/local/bin folder(here NNN is 230 version no.)

sudo mv ~/Downloads/checker-230/* /usr/local/bin



Basic Usage


scan- build tests our code by compiling our Xcode project and studying it for defects during the build process. Initially, we are required to change some of the settings in our XcodeProject.

  1. Select the xcodeproject group, and click on Get Info.

  2. In General tabs, select “Base SDK” - “iPhone Simulator 3.0”

  3. In Build tab, select “Base SDK” - iPhonesimulator3.0” & Valid Architectures – i386.

  4. Make Code Signing Identity - “Don't Code Sign”

  5. Select “Any iPhone OS Device” - “Don't Code Sign”

    And then

To check our code, we just invoke scan-build from the command line at the top level of any one of your project directories.

  1. Still in Terminal.app, change into one of your project directories

  2. Run scan-build of your Xcode project.

scan-build -k -V xcodebuild -configuration Debug -s iphonesimulator3.0

Customizing your Output Report

After running scan-build for sometimes, the first thing you might want to do is tell scan-build to put its report in a different place. To do that, simply specify the output folder on the command line like so:

scan-build -o /custompath/for/report xcodebuild -configuration Debug -s iphonesimulator3.0


  • If you are using iphone SDK 3.0 on Snow Leapord, then Clang Static Analyzer is coming in-built in the IDE.

It will be great to use it for better programming analysis to judge the memory management.

Thanks

Tuesday, August 18, 2009

Cocoa with JSON data using SBJSon

Hi all,

This is my very first blog. For this blog, I would like to thank to Stig Brautaset for bringing out an excellent JSON Parser " SBJSON".
Firstly download SBJSON framework from

There are two ways to include SBJSON framework into the code.

1) Either include this framework into the framework folder of the application

2) Or Copy all the classes into 1 folder in Classes folder.

Here are the list of the classes available in SBJSON framework


"SBJSON.h"

"NSObject+SBJSON.h"

"NSString+SBJSON.h"

"SBJsonParser.h"

"SBJsonWriter.h"

"SBJsonBase.h"


And in all these

------

"SBJSON.h"

"NSObject+SBJSON.h"

"NSString+SBJSON.h"

------


the above 3 classes are only imported in JSON.h file


And now import JSON.h file into the class, where we are going to communicate through the HTTP JSON response into Cocoa.



Now I am going to share the way to interact with the server for GET request


1)

- (NSMutableArray *) downloadGetData:(NSString *)urlString

{

id response = [self objectWithGetUrl:[NSURL URLWithString:[NSString stringWithFormat:@"%@" ,urlString]]];

NSMutableArray *record = (NSMutableArray *)response;

return record;

}


Here we are taking the URL in string where we want to hit, to get the response, will call the method objectWithGetUrl:(NSURL*)type to get the response of the type id assigning it the value into NSURL format by converting the string into NSURL.




2)

- (id) objectWithGetUrl:(NSURL *)url

{

SBJSON *jsonParser = [SBJSON new];

NSString *jsonString = [self stringWithGetUrl:url];

// Parse the JSON into an Object

id data = [jsonParser objectWithString:jsonString error:NULL];

//Release SBJSon Object

[jsonParser release];

return data;

}


Here, Create a SBJSON object to parse JSON into a native Cocoa object using [SBJSON new]. This object will be in autorelease pool ( it means, it will automatically loose its memory when it will be not in scope).
These we will call the the local method stringWithGetUrl. and the url parameter which we have got in this method will be assign to stringWithGetUrl's parameter.

Then using the JSONParser class

- (NSString *)stringWithGetUrl:(NSURL *)url

{

@try {

NSInteger internetConnectionAvailability = [self internetConnectionAvailable];

if(internetConnectionAvailability == kInternetConnectionAvailable)

{

NSInteger timeInterval = [NSLocalizedString(@"Time Interval", @"Time Interval") intValue];

NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url

cachePolicy:NSURLRequestReturnCacheDataElseLoad

timeoutInterval:timeInterval];

// Fetch the JSON response

NSData *urlData;

NSURLResponse *response;

NSError *error;

// Make synchronous request

urlData = [NSURLConnection sendSynchronousRequest:urlRequest

returningResponse:&response

error:&error];

if([urlData length] == 0)

{

UIAlertView *alertTest = [[UIAlertView alloc]

initWithTitle:@"Sorry !"

message:@"No Service is available"

delegate:self

cancelButtonTitle:@"OK"

otherButtonTitles:nil];

[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

[alertTest show];

[alertTest autorelease];

return @"";

}

else {

return [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];

}

// Construct a String around the Data from the response

}

}

@catch (NSException * e)

{

NSString *msg = [NSString stringWithFormat:@"%@",[e description]];

NSLog(@"hi NSException %@",[e description]);

UIAlertView *errorAlertView = [[[UIAlertView alloc] initWithTitle:@"Exception !" message:msg delegate:self cancelButtonTitle:@"No" otherButtonTitles:nil,nil] autorelease];

[errorAlertView show];

}

@finally

{

}

return @"";

}


Here we have requested the url with Get type request, and getting the result into byte format, and then we will convert it into NSString, the json String, which we are converting to JSON using json parser.


Now here, we will discuss, how could we request the URL with type POST and sending JSON data in request

@try

{

if([self internetConnectionAvailable] == kInternetConnectionAvailable)

{

SBJSON *jsonParser = [SBJSON new];

jsonParser.humanReadable = YES;

NSString *jsonString = [NSString stringWithFormat:@"%@", [refinements JSONFragment], nil];

NSString *changeJSON = [NSString stringWithFormat:@"%@", [refinements JSONFragment], nil];

#ifdef TARGET_IPHONE_SIMULATOR

NSLog(jsonString);

#endif

changeJSON = [NSString stringWithFormat:@"categoryId=%@&refinements=%@",categoryId,changeJSON];

NSData *requestData = [NSData dataWithBytes: [changeJSON UTF8String] length: [changeJSON length]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:[NSString stringWithFormat: @"%@results", ServerUrl]]];

NSString *postLength = [NSString stringWithFormat:@"%d", [requestData length]];

[request setHTTPMethod: @"POST"];

[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

[request setHTTPBody: requestData];

//Data returned by WebService

NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];

NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];

categorySearchList = (NSMutableDictionary*) [jsonParser objectWithString:returnString error:NULL];

[[GlobalObjects sharedInstance] setCategorySearchList:categorySearchList];

[jsonParser release];

[request release];

request = nil;

[returnString release];

returnString = nil;

[[GlobalObjects sharedInstance] setCategorySearchList:categorySearchList];

[NSThread detachNewThreadSelector:@selector(saveResultForCategoryinCache) toTarget:self withObject:nil];

}

}

@catch (NSException * e)

{

NSString *msg = [NSString stringWithFormat:@"%@",[e description]];

NSLog(@"hi NSException %@",[e description]);

UIAlertView *errorAlertView = [[[UIAlertView alloc] initWithTitle:@"Exception !" message:msg delegate:self cancelButtonTitle:@"No" otherButtonTitles:nil,nil] autorelease];

[errorAlertView show];

}

@finally

{

}