Sunday 16 October 2011

Data Sharing on iCloud from iPhone/iPad with iOS 5.0

In Apple's recent release iOS 5.0, major feature is iCloud service. iCloud is the service for sharing data of your application which is running in different devices. iCloud service can be use in application many different ways i.e. data sharing (where you can set values on key like for application NSUserDefaults), Document sharing and database sharing by using core data.

For iCloud integration, you must have Xcode 4.2 with iOS 5.0 device. You can not test this feature in iPhone/iPad Simulator.

Here is the some easier steps for data sharing :
  1. Create application specific (i.e. com.your company.applicationname) apple id from Apple Developer Portal.
  2. Enable iCloud service for that App ID and create provisioning profile and install it on your mac.
  3. Create new project in Xcode with same app Id earlier created.
  4. Select target of application, click on summary and scroll down to Entitlement section. Click on custom entitlements.




  5. Above action will add "$ProjectName.Entitlement" file in your project. Add following keys in entitlement.
    com.apple.developer.ubiquity-container-identifiers as array
    com.apple.developer.ubiquity-kvstore-identifier as string




  6.  Now add valur for key with $TeamID.com.yourcompany.applicationName. Don't bother about TeamID. There are two ways to find Team ID. First, open provisioning profile into "TextEdit", you will find as below image. You can also find Team Id from member center -> Account Info.


  7. Provisioning Profile


    Member Center




  8. That's it from configuration side, Now you can add code

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSURL *iCloudURL = [fileManager URLForUbiquityContainerIdentifier:@"$TeamID.com.yourcompany.applicationname"];
    NSLog(@"%@", [iCloudURL absoluteString]);

    //iCloudURL == nil if iCloud is not supported or enable.

    if(iCloudURL){
           NSUbiquitousKeyValueStore *iCloudStore = [NSUbiquitousKeyValueStore defaultStore];
          [iCloudStore setString:@"Success" forKey:@"iCloudStatus"];
          [iCloudStore synchronize]; // For Synchronizing with iCloud Server
          NSLog(@"iCloud status : %@", [iCloudStore stringForKey:@"iCloudStatus"]);
    }
  9. You can also verify data storage from iPhone Settings -> iCloud -> Storage & Backup -> Manage Storage. Also, In Mac -> System Preference -> iCloud -> Manage Storage.