CloudKit how to modify existing record (swift 3) - swift

How can I modify an existing CloudKit record?
I receive a record from CloudKit with this code:
let name = tmpVar as! String
let container = CKContainer.default()
let privateDatabase = container.privateCloudDatabase
var predicate = NSPredicate(format: "email == %#", name)
var query = CKQuery(recordType: "MainTable", predicate: predicate)
privateDatabase.perform(query, inZoneWith: nil) { (results, error) -> Void in
if error != nil {
pass
}
else {
if (results?.count)! > 0 {
for result in results! {
self.likedArr.append(result)
}
if let checker = self.likedArr[0].object(forKey: "like") as? String {
print ("CHEKER IS \(checker)")
let intChecker = Int(checker)
let result = intChecker! + 1
} else {
print ("EMPTY")
}
} else {
print ("Login is incorrect")
}
OperationQueue.main.addOperation({ () -> Void in
// self.tableView.reloadData()
// self.tableView.isHidden = false
// MBProgressHUD.hide(for: self.view, animated: true)})}
and how to return it back modified value of "like" key to the owner "name"?

When you get the records from the cloud, you can cast them to CKRecords.
In this CKRecord object you just modify the values you want to update, and then save it all again to the cloud. The CKRecordId must be the same, otherwise you'll just make a new record.
here is how to modify the records:
MyCKRecord.setValue(object, forKey: "myKey")

When you call the query, you get an array of CKRecord objects. Use the subscript to edit the record:
record["key"] = value as CKRecordValue
when you're finished, take the CKRecord and use either CKModifyRecordsOperation or CKDatabase.save(_:completionHandler:) to save it back to the server.

Sharing my solution:
self.likedArr[0].setValue(1, forKey: "like")
let saveOper = CKModifyRecordsOperation()
saveOper.recordsToSave = self.likedArr
saveOper.savePolicy = .ifServerRecordUnchanged
saveOper.modifyRecordsCompletionBlock = { savedRecords, deletedRecordIDs, error in
if saveOper.isFinished == true {
}
}
privateDatabase.add(saveOper)

Related

How to append a record in core data entity having relation one to many

I have two entities of Mobile and User in which Mobile has attribute name and user also has a attribute of name. User can has multiple mobile but mobile has can only one user. Scenario is that when ever I enter a name for user which is already present in User entity it should update that user.mobile set rather than duplicating a new user.
These are my save and fetch functions
func save () {
if context.hasChanges {
do {
try context.save()
print("saved succesfully")
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
func fetch<T: NSManagedObject>( _ objectType: T.Type) -> [T] {
let entityName = String(describing: objectType)
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
do {
let fetchedObjects = try context.fetch(fetchRequest) as? [T]
return fetchedObjects ?? [T]()
} catch {
print(error)
return [T]()
}
}
This is how i am adding
users = persistenceManager.fetch(User.self)
if users.count > 1 {
for val in users {
if val.name == "Umar" {
val.addToDevice(device)
device.user = val
persistenceManager.save()
}
else if val.name != nil {
user.name = "Umar"
user.addToDevice(device)
device.user = user
persistenceManager.save()
}
}
Your question lacks some details. BUt let me assume I understand you correctly.
let userName = "some name from user input"
let user = MOUser.getUser(context, name: userName, createIfMissing: true)
// here you have user with name required and not duplicated if already exists
device.user = user
And add static function either to your user class or to db coordinator
static func getUser(moc: NSMaagedObjectContext, name: String, createIfMissing: Bool) -> MOUser? {
let request: NSFetchRequest<MOUser> = MOUser.fetchRequest()
request.predicate = NSPredicate(format: "\(#keyPath(MOUser.name)) = %#", name)
request.fetchLimit = 1
var result: MOUser? = (try? moc.fetch(request))?.first
if result == nil && createIfMissing {
result = MOUser(context: moc)
result?.name = name
}
return result
}

Saving & Fetching CloudKit References

I'm having trouble creating with CloudKit References. Data is being saved into CloudKit but its not referencing its parent (list). Don't know what i'm doing wrong, any help would be much appreciated!
Saving Method
var list: CKRecord?
var item: CKRecord?
#objc func save() {
let name = nameTextField.text! as NSString
//Fetch Private Database
let privateDatabase = CKContainer.default().privateCloudDatabase
if item == nil {
//Create Record
item = CKRecord(recordType: RecordTypeItems)
//Initialization Reference
guard let recordID = list?.recordID else { return }
let listReference = CKRecord.Reference(recordID: recordID, action: .deleteSelf)
item?.setObject(listReference, forKey: "list")
}
item?.setObject(name, forKey: "name")
//Save Record
privateDatabase.save(item!) { (record, error) in
DispatchQueue.main.sync {
self.processResponse(record: record, error: error)
}
}
}
Fetch Method
var list: CKRecord!
var items = [CKRecord]()
private func fetchItems() {
//Fetch Private Database
let privateDatabase = CKContainer.default().privateCloudDatabase
//Initialize Query
guard let recordID = list?.recordID else { return }
let reference = CKRecord.Reference(recordID: recordID, action: .deleteSelf)
let query = CKQuery(recordType: RecordTypeItems, predicate: NSPredicate(format: "list == %#", [reference]))
//Configure Query
query.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
//Peform Query
privateDatabase.perform(query, inZoneWith: nil) { (records, error) in
DispatchQueue.main.sync {
self.processResponseForQuery(records: records, error: error)
}
}
}
Where you are creating your query to retrieve items referencing the list, should the list reference in the predicate format string be inside an array? If you create the item's reference like item?.setObject(listReference, forKey: "list"), CloudKit will infer the list field to be a single CKRecord.Reference, so the query would be:
let query = CKQuery(recordType: RecordTypeItems, predicate: NSPredicate(format: "list == %#", reference))

DynamoDB scan : Does not return correct values

I have written the following function but I have a problem with its returning value.
In my console I can see the results pulled from AWS dynamoDB, I can even display it. As you can see, I am printing item variable.
I instantiated an array in my function and append each item pulled from AWS to it but it returning nil.
Can you please see what I miss in my code thanks.
func scanClientList(_ startFromBeginning: Bool) -> [Client]{
var clients = [Client]()
UIApplication.shared.isNetworkActivityIndicatorVisible = true
let dynamoDBObjectMapper = AWSDynamoDBObjectMapper.default()
let queryExpression = AWSDynamoDBScanExpression()
//queryExpression.exclusiveStartKey = self.userId
queryExpression.limit = 20
dynamoDBObjectMapper.scan(Client.self, expression: queryExpression).continueWith(executor: AWSExecutor.mainThread(), block: { (task:AWSTask!) -> AnyObject! in
if let paginatedOutput = task.result {
for item in paginatedOutput.items as! [Client] {
print("ITEMS: \(item)")
clients.append(item)
}
if paginatedOutput.lastEvaluatedKey == nil {
}
}
UIApplication.shared.isNetworkActivityIndicatorVisible = false
if let error = task.error as? NSError {
print("Error: \(error)")
}
return nil
})
return clients
}
Actually my function here works perfectly, I didn't initialize the variable clients in the functions
I had something like
var clients = [Client]()?
and changed it to
var clients:Array<Client> = []

Cannot convert value of type 'String?!' to expected argument type 'Notifications'

I am trying to check the id of a record before I put it into the array, using xcode swift
here is the code. But, i get the following error
Notifications.swift:50:46: Cannot convert value of type 'String?!' to expected argument type 'Notifications'
on this line
*if (readRecordCoreData(result["MessageID"])==false)*
Please can some one help to explain this error
import CoreData
struct Notifications{
var NotifyID = [NSManagedObject]()
let MessageDesc: String
let Messageid: String
init(MessageDesc: String, Messageid:String) {
self.MessageDesc = MessageDesc
self.Messageid = Messageid
// self.MessageDate = MessageDate
}
static func MessagesWithJSON(results: NSArray) -> [Notifications] {
// Create an empty array of Albums to append to from this list
var Notification = [Notifications]()
// Store the results in our table data array
if results.count>0 {
for result in results {
//get fields from json
let Messageid = result["MessageID"] as! String
let MessageDesc = result["MessageDesc"] as? String
let newMessages = Notifications(MessageDesc: MessageDesc!, Messageid:Messageid)
//check with id's from core data
if (readRecordCoreData(result["MessageID"])==false)
{
Notification.append(newMessages)
}
}
}
return Notification
}
//check id
func readRecordCoreData(Jsonid: String) -> Bool {
var idStaus = false
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
//2
let fetchRequest = NSFetchRequest(entityName: "ItemLog")
//3
do {
let resultsCD = try! managedContext.executeFetchRequest(fetchRequest)
if (resultsCD.count > 0) {
for i in 0 ..< resultsCD.count {
let match = resultsCD[i] as! NSManagedObject
let id = match.valueForKey("notificationID") as! String
if (Jsonid as String! == id)
{
idStaus = true
}
else{
idStaus = false
}
}
}
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
return idStaus
}
One of your methods is static and the other one is not :
func readRecordCoreData(Jsonid: String) -> Bool
static func MessagesWithJSON(results: NSArray) -> [Notifications]
Depending on what you want to accomplish you could declare both static, none, or replace
//check with id's from core data
if (readRecordCoreData(result["MessageID"])==false)
{
Notification.append(newMessages)
}
By
//check with id's from core data
if (Notifications.readRecordCoreData(Messageid)==false)
{
Notification.append(newMessages)
}
Not sure if the code will work past compilation however as there are many readability issues

How can I speed up performQuery in Swift?

So I am creating this app that uses CloudKit to save and fetch images and text from the Cloud. The problem is that I can only access the results after the whole fetch is done. I would like to be able to fetch each record individually as it is fetched. Here is the code.
func fetchPost() {
spinner.startAnimating()
if imageView.image != nil {
spinner.alpha = 0
}
var imageData = [UIImage]()
var text = [String]()
let predicate = NSPredicate(value: true)
let sort = NSSortDescriptor(key: "creationDate", ascending: false)
let query = CKQuery(recordType: "Post",
predicate: predicate)
query.sortDescriptors = [sort]
publicDB.performQuery(query, inZoneWithID: nil) {
results, error in
if error != nil {
dispatch_async(dispatch_get_main_queue()) {
println("Query failed")
return
}
} else {
println("test")
var number = 0
for record in results {
if let pictureRecord = record as? CKRecord {
let post = Post(record: pictureRecord, database: self.publicDB)
let postImageData = post.imageData
let postText = post.text
self.images.append(UIImage(data: postImageData)!)
self.texts.append(postText)
println("\"\(postText)\" is the text. Fetch successful.")
if number == 0 {
self.imageView.image = self.images[0]
self.nameLabel.text = self.texts[0]
}
++number
} else {
println("Records failed")
}
}
}
self.spinner.stopAnimating()
self.spinner.alpha = 1
}
}
Thanks!
If you use CKQueryOperation you can set a callback (recordFetchedBlock) that will be called for each record as it is fetched from the server.