Sunday, 16 December 2012

DropBox integration to iPhone Application

In one of my iPhone application i wanted to integrate DropBox to share things.
I just visited the DropBox developer site : https://www.dropbox.com/developers/reference/sdk and downloaded the sdk for iOS and the tutorial for integration.
DropBox has really made it very easy to integrate and have provided an awesome documentation.
I followed the steps, made some modifications and i was done.

You can download the sample code:
Download

Saturday, 8 December 2012

Parse CSV file in Objective C


Sometimes we have a bulk of data in a .csv file which we need to add or access in our iOS Application.
For this we can add that .csv file in application's bundle, fetch data from it and store it in an NSArray for use.

Follow the steps:

1. Once list of Country Names so i downloaded the full-country-list.csv from internet and added it in my application's bundle by simply dragging it.
2. Now i just located that file path and stored in 'strPath' variable, then stored its contents and encoding type in 'strFile' variable.
3. Checked if file is present and i am able to read it.
4. Now i allocated & initialized an NSArray object 'arrayCountry'.
5. To parse file use 'strFile componentsSeparatedByString:@"\n"' and store it in arrayCountry. This .csv file is seperated with new line character, if .csv is seperated by comma use ',' instead of '\n'.
6. And we are done with parsing .csv file and we have all country names in arrayCountry NSArray object.


    NSString *strPath = [[NSBundle mainBundle] pathForResource:@"full-country-list" ofType:@"csv"];
    NSString *strFile = [NSString stringWithContentsOfFile:strPath encoding:NSUTF8StringEncoding error:nil];
    if (!strFile) {
        NSLog(@"Error reading file.");
    }
    NSArray *arrayCountry = [[NSArray alloc] init];
    arrayCountry = [strFile componentsSeparatedByString:@"\n"];
    
    for(NSString *countryname in arrayCountry) {
        NSLog(@"%@", countryname);
        
    }
    NSLog(@"Countries Count: %i", [arrayCountry count]);

Code: Download

Thursday, 22 November 2012

Integrating Facebook and Twitter using Social Framework iOS 6

Lets checkout how to integrate and start sharing using Facebook and Twitter using Social Framework provided in iOS 6



























































































































































































































































Source code: Download


Launch iOS Application From Safari Using CustomURLScheme


If you want to take user back from Safari to your iOS Application, you can achieve it using custom url scheme.
Follow the steps:

1. Open -info.plist file and add

<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>myapplicationurl</string>
</array>
</dict>
</array>

2. Above code will register a custom url for your application.
3. You can also pass parameters (query string) to it:
myapplicationurl://
myapplicationurl://?key1=value1&amp;key2=value2
4. When this url is called from Safari iPhone SDK sends message to UIApplicationDelegate

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
 // You are back to your application.
 NSLog(@"Yeah!!! We are back to Application from Safari");
 return YES;
}

5. Above method in UIApplicationDelegate will be called and we are navigated to our Native iOS app from Safari.

This same technique is used by Facebook iOS sdk.
Special thanks to :
http://mobiledevelopertips.com/cocoa/launching-your-own-application-via-a-custom-url-scheme.html

First download source code from here: Download

After downloading run application and hit 'Open Safari' button it will take you to safari and will show you this page, now on this page hit below link 'Open Application from SAFARI' you are navigated back to application.

Open Application from SAFARI

Friday, 2 November 2012

Integrating Pinterest in iOS Application


Pinterest do not provide api's for integration yet.
So in order to achieve it we need to use UIWebView in iOS App.

Follow below steps:
1. Take a UIViewController containing two buttons, one UIWebView.
2. Generate HTML programatically and pass it to loadHTMLString in UIWebView.
3. On touchup-inside of first button, load html string which will open Pinterest in UIWebView.
4. Here pass your custom description and image url which you want to pin.
5. On touchup-inside of second button, close/hide the UIWebView.
















Download Code from here: PinterestiOSIntegration

Above link helped me out.

Wednesday, 24 October 2012

Open htaccess Password Protected Web-Page in UIWebView


In some cases we want to access a password protected (htaccess) webpage from UIWebView iPhone.
So for this we need add username and password between 'http://' and 'page url'. 
e.g. @"http://username:password@192.165.1.11/mypage"


NSString *url = @"http://username:password@192.165.1.11/mypage";
[webViewForhtaccessPageRendering loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString: url]]];

here webViewForhtaccessPageRendering is UIWebVIew.

Monday, 22 October 2012

UITableView - Add or Remove Rows Dynamically (Objective C & Swift Source codes)


In some situations we need to add or remove rows dynamically from a UITableView.
We can achieve it very easily, just got through the tutorial :

1. Create a new project.
2.  In AppDelegate implementation file create an object of UINavigationController (navController here).




3. Add object of UIViewController (viewController here) as rootviewcontroller of UINavigationController.
4. In ViewController.xib nib file take a UITableView.
5. Set delegate and datasource of UITableView to File's Owner.
6. Create an IBOutlet to UITableView (tableViewForScreen here) in ViewControler.h header file.













7. Declare an object of NSMutableArray (arrayForTableContent here) in ViewControler.h header file.
8. In ViewController.m file in viewDidLoad method set edit and add buttons as leftBarButtonItem and rightBarButtonItem respectively.
9. Initialize arrayForTableContent array and add objects to it.
























10. Now set number of rows, section of UITableView.
11. In cellForRowAtIndexPath set the table cell label.














12. In  'setEditing:(BOOL)editing animated:(BOOL)animated' method set tableview editing and animated.





























13. In commitEditingStyle forRowAtIndexPath method:
      If editingStyle is delete remove object from array.
      And using 'deleteRowsAtIndexPaths withRowAnimation'; remove the row at provided index path and with animation style.

























14. To insert rows dynamically call insertNewObject method on rightbarbuttonitem.
15. In insertNewObject method add an object to array using 'insertObject atIndex'.
16. And for inserting row to tableview use 'insertRowsAtIndexPaths withRowAnimation' method.

























You can download Code
Swift: Swift_Editable_UITableView

Friday, 12 October 2012

Implementing iAd in iPhone/iPad/iPod Touch Application

Implementing iAds in your iPhone/iPad Application is really very simple.

1. First add "iAd.framework" Framework from Targets -> Build Phases -> Link Binary With Libraries.



2. In ViewController.h #import  <iAd/ADBannerView.h>
3. Take ADBannerViewDelegate.




4. Now take a ADBannerView in ViewController.xib.
5. Set IBOutlet to ADBannerView (as iADBannerView here).
6. Set delegate of ADBannerView to File Owner(self).




7. In ViewController.m set iADBannerView as Hidden in viewDidLoad method. Which will hide the ADBannerView while loading controller screen.
8. Now add delegate methods of ADBannerView mentioned below:

- (void)bannerViewDidLoadAd:(ADBannerView *)banner;

- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error;

9. In bannerViewDidLoadAd method unhide the ADBannerView. As method name specifies this method is executed when ADBannerView loads.

10. If there is any issue in loading ADBannerView the bannerView: didFailToReceiveAdWithError is executed.






11. Now when top tap on ADBannerView it will show you a "Test Advertisement" screen as shown in below snapshot. This means you are all done, and ready to go.





You can download sample code from here: iAdDemo





Tuesday, 9 October 2012

Validate and Parse NSURL in Objective C


I need to check if Url is valid or not in my iPhone application so i found below snippet from  


We can validate a url by simply using Foundation Framework as follows: 

        NSURL *myURL = [NSURL URLWithString:@"http://google.com"];
        if (myURL && myURL.scheme && myURL.host) {
            NSLog(@"URL is validated");
        } else {
            UIAlertView *alertMsg = [[UIAlertView alloc] initWithTitle:@"Error" 
                                     message:@"URL is invalid" delegate:nil 
                                     cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alertMsg show];
            [alertMsg release];
        }


Output: 
URL is validated


Above can be achieved using RegexKit also as follows:

    NSString *regexExpression = @"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";
    NSString *urlString = @"http://google.com";
    
    NSString *matchedString = [urlString stringByMatching:regexExpression];

if you want to validate url string like: www.google.com just replace
(http|https):// with ((http|https)://)* 

You can download RegexKit from 
http://regexkit.sourceforge.net/


Some time we need to parse a NSURL and fetch a particular part out from it.
We can parse a NSURL as follows:

            NSURL *url = [NSURL URLWithString:@"https://www.google.co.in/search?q=validate+url+objective+c&oq=validate+url+objective+c&sugexp=chrome,mod=6&sourceid=chrome&ie=UTF-8"];

            NSLog(@"URL Scheme: %@", [url scheme]); 
            NSLog(@"URL Host: %@", [url host]); 
            NSLog(@"URL Port: %@", [url port]);     
            NSLog(@"URL Path: %@", [url path]);     
            NSLog(@"URL Relative path: %@", [url relativePath]);
            NSLog(@"URL Path components as array: %@", [url pathComponents]);        
            NSLog(@"URL Parameter string: %@", [url parameterString]);   
            NSLog(@"URL Query: %@", [url query]);       
            NSLog(@"URL Fragment: %@", [url fragment]);


Output:
 Scheme: https
 Host: www.google.co.in
 Port: (null)
 Path: /search
 Relative path: /search
 Path components as array: (
    "/",
    search
)
 Parameter string: (null)
 Query: q=validate+url+objective+c&oq=validate+url+objective+c&sugexp=chrome,mod=6&sourceid=chrome&ie=UTF-8
 Fragment: (null)











Thursday, 4 October 2012

Database implementation using SQLite in iOS Applications


SQLite: 
I have worked on Core Data and SQLite both, but i personally feel that using SQLite is a good choice.
Working on Database directly using SQLite is better than working on Core Data which actually works as a wrapper above SQLite.
We can easily fire complex sql queries on Database using SQLite to store, update or fetch data; which is a pathetic job using Core Data. 

Below is a simple demo app which will help you understand how to use SQLite to create database, store, update, fetch and delete records from database.

For using SQLite database in iPhone, iPad App first you need to link libsqlite3.0.dylib to your build target. 
To do this select 'Project' at top left navigation panel -> 'under Targets' select your build target -> then click on 'Build Phases' tab -> then in 'Link Binary With Libraries' click on '+' button and add libsqlite3.0.dylib.




 There are number of C functions contained within the libsqlite3.dylib library which can be used for sqlite implementation.

1. sqlite3_open() - This function is used to opens database. In case database does not exist, it creates one.
2. sqlite3_prepare_v2() – This function is used to prepares a SQL statement for execution.
3. sqlite3_step() – This function is used to executes a SQL statement previously prepared by the sqlite3_prepare_v2() function.
4. sqlite3_column_<type>() – This function is used to returns a data field from the results of a SQL retrieval operation. Where <type> is the type of the data to be extracted (int, text, blob, bytes, etc).
5. sqlite3_finalize() - This function is used delete a previously prepared SQL statement.
6. sqlite3_exec() – This function is used combine the functionality of sqlite3_prepare_v2(), sqlite3_step() and sqlite3_finalize() into a single function call.
7. sqlite3_close() – This function is used to close a database file previously opened.


Below is the code snippet for using sqlite implementation:

In header file:

In implementation file:







In xib file:


Here is the sample code: SQLITE_CODE

Saturday, 8 September 2012

NSUserDefaults



For storing data in iOS Device we have some options like NSUserDefaults, Plist file, Sqlite, Core Data.
Depending on our reqirement we switch on one of the option amongst these.

NSUserDefaults   - We store users preferences and settings here.
Plist File                - We store data in Plist if we dont have large data to persist. We store data in key-value pair. 
Core Data             - We store anything which we want to persist, we can execute predicated, fetch requests to retrieve data.
SQLite                   - We store anything which we want to persist, we can execute more complex queries directly to Database to fetch data/

Actually NSUserDefaults is a Plist file.
NSUserDefaults will store the users preferences into a Plist file into the Library/Preferences folder. So we can store whatever we can store in a Plist file.
There is no restriction on size of a Plist File. But one thing you might not forget is that when you store or read data in a Plist file whole contents of the file are loaded into memory which may effect the performance of application if you have huge data.

We can store data easily in NSUserDefaults:

[[NSUserDefaults standardUserDefaults] setInteger:1024 forKey:@"my_count"];
[[NSUserDefaults standardUserDefaults] synchronize];
Using above statements we can set int - 1024 to a key - my_count.

int myCount = [[NSUserDefaults standardUserDefaults] integerForKey:@"my_count"];
By using above statement we can fetch value for key - my_count.

Below are getter/setter method to store to or retrieve values from NSUserDefaults:
Setters Getters

setInteger:forKey: integerForKey:
setFloat:forKey: floatForKey:
setDouble:forKey: doubleForKey:
setBool:forKey: boolForKey:
setObject:forKey: stringForKey:
setObject:forKey: dataForKey:
setObject:forKey: objectForKey:
setObject:forKey: arrayForKey:
setObject:forKey: dictionaryForKey:
setObject:forKey: stringArrayForKey:

One important thing is if you are storing a Mutable Array - NSMutableArray to NSUserDefaults you will get an immutable Array - NSArray in return.
This means that values returned by NSUserDefaults are immutable.





Monday, 13 August 2012

Lightweight Database Migration in CoreData



Lightweight Migration:

This is an automatic feature of Core Data, but is limited to only simple migrations.
You can use this technique if the changes are among the following:
1. Adding a new attribute to an entity.
2. Renaming of an entity or an attribute.
3. Changing an attribute to optional or non-optional, whether it requires a value on creation.

Schema Changes, Versioning and Migrations
When you are developing an application you will almost never get the schema right the first time. So, Core Data has support for schema versioning and data migration. This allows you to define a new version of the Core Data schema by adding a new attribute or entity to the store. Then define how the store has to migrate from one change to another.


Creating a new xcdatamodel (Xcode 4.3.2)

If you want to do a lightweight migration first step is to create a new xcdatamodel for new schema.

1. Click on your xcdatamodeld file present in bundle.
2. Click on Editor Menu and select Add Model Version.
3.

4. Here specify the version name and Base Model and click Finish.
5. And you will find the newly created xcdatamodel file under the xcdatamodeld group.
6. Now click on xcdatamodeld in bundle and open File Inspector, under Versioned Core Data Model select the newly created xcdatamodel file.
7.

8. A green Tick will appear to left of the currently selected xcdatamodel file.
9.


10. And now you are done with data migration, now Core Data will automatically handle the new schema for the database.


11. Set the Persistent Store options for automatic migration in AppDelegate

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (__persistentStoreCoordinator != nil) {
return __persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"YOURDB.sqlite"];
//Enabling automatic migrations in persistent store coordinator
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
NSError *error = nil;
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return __persistentStoreCoordinator;
}