iCloud integration in Swift 3.0

Introduction of iCloud :

iCloud provide the free service to store data from device to iCloud platform, 
(Note : Some of limitation also) , and user can access their data form any device via AppleID. The main purpose is users easily put own data like images, videos, etc and also access the all stored items from any Apple device like iPhone, iPad, Mac etc.



We are providing the full steps of iCloud integration, Here we store images and text items on iCloud, Edit and delete functionality also in this tutorials with demo app.

Make provisional profile for iCloud Enable :

1 : Open Apple developer official site : https://developer.apple.com/

2 : Click on Member Centre and login developer centre.

3 : There are six options , Select Certificate , Identifier & Profile  




4 : Select Identifier > App IDs list display.



5 : Click on right corner + button and adding new Identifier.

6 : Adding details like 
  
     Name          : iCloudTest 
     Bundle ID : com.cloudone.userDetails


7 : Check mark on iCloud option and generate identifier.



8 : You can see here , iCloud is configurable but not enable.




9 : Click on Provisional profile and Select iOS App Development option.





10 : Select your App ID and Select all devices.





11 : Give the name of Profile and continue.




12 : Download the provisional profile, and double click on profile and installed provisional profile.







Xcode configuration : 


1 : Create project in Xcode > New > Project.

2: Check bundle Identifier which is same as developer account also check team of account.



3 : Choose provisional profile Build Setting > Code Signing.





4 : Go to capability and Select iCloud ON. When you select cloudKit option of radio button then its automatically take identifier.




5 : Go to developer site and you can see the iCloud configurable is enable.






CloudKit Dashboard : 

1 : For cloudKit Dashboard open https://icloud.developer.apple.com/dashboard/ 

2 : CloudKit dashboard at leftSide have your project in which you integrate the cloud. So Select the project with its identifier, Your project identifier automatically display after you complete above process.


  



3. Click on the + plus button and adding the record Schama name : UserDetails . The UserDetails Schama to adding more field according to requirements.







4. UserDetails is one type of tableName on iCloud. Adding four field to store the data on iCloud like firstName , lastName , emailID and Photos. The firstName , lastName , emailID FieldType is String and Photos fieldType is Asset. Click on Save button. So Create one table Name UserDetails on iCloud with four fields and you can store the data on iCloud.  








Coding  :

First of all you have to import the iCloud in the project before the use. import iCloud in the file.
import CloudKit
Make an object of  CKContainer.
let container = CKContainer.default()
iCloud have two types of database : PrivateCloud and PublicCloud, In this example we are store in private.
let publicDB = container.privateCloudDatabase

Add record on iCloud  :
@IBAction func click_AddCloud(_ sender: AnyObject) {

        let publicDB = container.privateCloudDatabase
        let userData = CKRecord(recordType: "UserDetails")
        userData.setValue(txtFirstName.text, forKey: "firstName")
        userData.setValue(txtLastName.text, forKey: "lastName")
        userData.setValue(txtEmailID.text, forKey: "emailID")

        if (self.imageURLs == nil) {
            self.imageURLs = URL(fileURLWithPath: Bundle.main.path(forResource: "ima", ofType: "jpg")!)
        }

        print(imageURLs)
        let imageAsset = CKAsset(fileURL: imageURLs)
        userData.setObject(imageAsset, forKey: "Photos")

        DispatchQueue.main.async {
            publicDB.save(userData, completionHandler: { (record, error) -> Void in
                // print("saved")
                if error != nil{


                     let alertController = UIAlertController(title: "Error", message: "Opps!. Somthing wrongs.", preferredStyle: .alert)

                     let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (action) in
                        _ = self.navigationController?.popViewController(animated: true)
                     })

                     alertController.addAction(action)
                     self.present(alertController, animated: true, completion: nil)

                }else{
                     let alertController = UIAlertController(title: "Success", message: "Data Saved Successfully on cloud.", preferredStyle: .alert)
                        let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (action) in
                            _ = self.navigationController?.popViewController(animated: true)
                        })
                     alertController.addAction(action)
                     self.present(alertController, animated: true, completion: nil)

                }
            })
        }
}

Get record from iCloud :
func fetchResults(){

        let container = CKContainer.default()
        let privateDatabase = container.privateCloudDatabase
        let predicate = NSPredicate(value: true)
        let query = CKQuery(recordType: "UserDetails", predicate: predicate)

        privateDatabase.perform(query, inZoneWith: nil) { (results, error) -> Void in
            if error != nil {
                print(error?.localizedDescription)

                MBProgressHUD.hide(for: self.view, animated: true)
            }
            else {
                print(results)

                for result in results! {
                    self.arrayDetails.append(result)
                }

                OperationQueue.main.addOperation({ () -> Void in
                    self.tableView.reloadData()
                    self.tableView.isHidden = false
                    MBProgressHUD.hide(for: self.view, animated: true)
                })
            }
        }

}

Edit record on iCloud :
@IBAction func click_EditCloud(_ sender: AnyObject) {     

        let publicDB = container.privateCloudDatabase
        let userData = CKRecord(recordType: "UserDetails")
        userData.setValue(txtFirstName.text, forKey: "firstName")
        userData.setValue(txtLastName.text, forKey: "lastName")
        userData.setValue(txtEmailID.text, forKey: "emailID")

        print(imageURLs)

        let imageAsset = CKAsset(fileURL: imageURLs)
        userData.setObject(imageAsset, forKey: "Photos")



        let saveRecordsOperation = CKModifyRecordsOperation(recordsToSave: [userData], recordIDsToDelete: [editableData.recordID])
        saveRecordsOperation.recordsToSave = [userData]
        saveRecordsOperation.savePolicy = .ifServerRecordUnchanged

        saveRecordsOperation.modifyRecordsCompletionBlock = { savedRecords, deletedRecordsIDs, error in
            OperationQueue.main.addOperation({ () -> Void in
                if error != nil {
                    let alertController = UIAlertController(title: "Error", message: error!.localizedDescription, preferredStyle: .alert)
                    let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (action) in
                        _ = self.navigationController?.popViewController(animated: true)
                    })
                    alertController.addAction(action)
                    self.present(alertController, animated: true, completion: nil)

                } else {
                    let alertController = UIAlertController(title: "Success", message: "Data Saved Successfully on cloud.", preferredStyle: .alert)
                    let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (action) in
                        _ = self.navigationController?.popViewController(animated: true)
                    })
                    alertController.addAction(action)
                    self.present(alertController, animated: true, completion: nil)

                }
                MBProgressHUD.hide(for: self.view, animated: true)
            })


        }

        publicDB.add(saveRecordsOperation)
}

Delete record from iCloud :
func deleteRecords(){

        MBProgressHUD.showAdded(to: self.view, animated: true)
        let selectedRecordID = self.arrayDetails[indexPath.row].recordID
        let container = CKContainer.default()
        let privateDatabase = container.privateCloudDatabase
        privateDatabase.delete(withRecordID: selectedRecordID, completionHandler: { (recordID, error) -> Void in
            if error != nil {
                print(error)
            }
            else {
                OperationQueue.main.addOperation({ () -> Void in
                    self.arrayDetails.remove(at: indexPath.row)
                    MBProgressHUD.hideAllHUDs(for: self.view, animated: true)
                    self.tableView.reloadData()
                })
            }
        })

 }


The above code is in swift 3.0 and working.


OUTPUT  : 


if any type of query of code then contact to me via comments.

Thanks




iCloud integration in Swift 3.0 iCloud integration in Swift 3.0 Reviewed by Kirit Modi on 11:24:00 Rating: 5

No comments:

Powered by Blogger.