How do I set the record name myself when recording on CloudKit? - swift

I can change the record name on the website. I couldn't find a way with the code.
let cloudsave = CKRecord(recordType: "iEmotion")
let recordName = CKRecord.ID(recordName: "1")
privateDatabase.save(cloudsave) { (savedRecord, error) in
if error == nil {
print("SUCCESSFUL") }
else {"ERROR"}
}
I don't want it saved as a UUID.

This should help:
let recordName = CKRecord.ID(recordName: "1")
let cloudsave = CKRecord(recordType: "iEmotion", recordID: recordName)
privateDatabase.save(cloudsave) { (savedRecord, error) in
if error == nil {
print("SUCCESSFUL") }
else {"ERROR"}
}

Related

Swift Core Data - handling empty fetch result

I have a simple entity, a stationID and a type, both Strings
I use this method to search for a type for a given stationID,
func returnStationType(stationTypeId: String) -> PersistantStationType {
let context = container.viewContext
let request = PersistantStationType.fetchRequest() as NSFetchRequest<PersistantStationType>
request.predicate = NSPredicate(format: "%K == %#", #keyPath(PersistantStationType.stationId), stationTypeId as CVarArg)
do {
let result = try context.fetch(request)
if result.count != 0 {
let fetchedStationType = result.first!
return fetchedStationType
} else { print("4 Fetch result was empty for specified stationid: \(String(describing: stationTypeId))")
}
} catch { print("Fetch on goal id: \(String(describing: stationTypeId)) failed. \(error)") }
return PersistantStationType.init()
}
I call the method here:
let persistentStationType = persistenceController.returnStationType(stationTypeId: closestStation.id)
let stationType = persistentStationType.type?.lowercased().capitalized
let realName = helper.returnRealName(stationType: stationType ?? "None")
let imageName = helper.returnStationTypeImage(stationType: stationType ?? "None")
If a stationId is not found - so empty result I get a crash in the code(Bad Exec/ Access) where I call the method - not in the method itself. (I'm not surprised by this but i'm not sure how to handle it)
I can't use if let on the method .. .it's not an optional. Should I be returning an empty object and check for It when the fetch result is empty?
Thanks for any help.
I would declare the function to return an optional and return nil when nothing is found
func returnStationType(stationTypeId: String) -> PersistantStationType? {
let context = container.viewContext
let request: NSFetchRequest<PersistantStationType> = PersistantStationType.fetchRequest()
request.predicate = NSPredicate(format: "%K == %#", #keyPath(PersistantStationType.stationId), stationTypeId)
do {
let result = try context.fetch(request)
if result.count != 0 {
return result[0]
} else {
print("4 Fetch result was empty for specified stationid: \(String(describing: stationTypeId))")
return nil
}
} catch {
print("Fetch on goal id: \(String(describing: stationTypeId)) failed. \(error)")
return nil
}
}
If on the error hand it is considered an error if more than one objects (or none) exists for an id then it would be better to throw an error in those situations
func returnStationType(stationTypeId: String) throws -> PersistantStationType {
let context = container.viewContext
let request: NSFetchRequest<PersistantStationType> = PersistantStationType.fetchRequest()
request.predicate = NSPredicate(format: "%K == %#", #keyPath(PersistantStationType.stationId), stationTypeId)
do {
let result = try context.fetch(request)
switch result.count {
case 0:
throw FetchError("No station type found for id \(stationTypeId)")
case 1:
return result[0]
default:
throw FetchError("Multiple station types found for id \(stationTypeId)")
}
} catch let error as NSError {
throw FetchError(error.localizedDescription)
}
}
struct FetchError: LocalizedError {
private let message: String
var errorDescription: String? {
message
}
init(_ message: String) {
self.message = message
}
}

Problems retrieving a record from CloudKit

Having problems retrieving a record from CloudKit..
My firstName and lastName of my CKRecord are showing up as "N/A" which the safety value from a nil coalescing as you'll see below
I double and triple checked (and beyond) that all the spellings were right.. so I'm good there. Here is my retrieve method..
func getProfile() {
//GETTING USER RECORD ID
CKContainer.default().fetchUserRecordID { id, error in
guard let id = id, error == nil else {
print(error?.localizedDescription)
return }
//GETTING RECORD ID
CKContainer.default().publicCloudDatabase.fetch(withRecordID: id) { record, error in
guard let record = record, error == nil else { return }
let profileReference = record["userProfile"] as! CKRecord.Reference
let profileRecordID = profileReference.recordID
print("Profile reference is",profileReference)
//PASSING REFERENCE TO GET CLIENT SIDE MODEL
CKContainer.default().publicCloudDatabase.fetch(withRecordID: profileRecordID) { profileRecord, error in
guard let profileRecord = profileRecord, error == nil else {
print(error!.localizedDescription)
return
}
//FOR SOME REASON MY PROFILE IS NOT RECEIVING THE RIGHT VALUES FOR FIRST AND LAST NAME, IT JUST SHOWS "N/A"
DispatchQueue.main.async {
let profile = Profile(record: profileRecord)
print("Retrieved Record is: ",profileRecord)
print("Retrieved name is: \(profile.firstName)")
firstName = profile.firstName
lastName = profile.lastName
}
}
}
}
}
And here is the model..
struct Profile {
let profileID: CKRecord.ID
let firstName: String
let lastName: String
init(record: CKRecord) {
profileID = record.recordID
firstName = record["firstName"] as? String ?? "N/A"
lastName = record["lastName"] as? String ?? "N/A"
}
}

shared database zones cannot be found

I have sucessfully shared a record from private database customzone.
share url Optional(https://www.icloud.com/share/0N9smwzXZ0gfumZv8jyVo7uag)
When I print shared record I get this:
record completion <CKShare: 0x106702100; participants=(
"<CKShareParticipant: 0x2817115e0; hasProtectionInfo=1, isCurrentUser=YES, participantID=E742CBD3-41C9-4A9E-A392-08914E8C1D37, permission=readWrite, role=owner, acceptanceStatus=Accepted, identity=<CKUserIdentity: 0x281815ce0; lookupInfo=<CKUserIdentityLookupInfo: 0x2832ba910; email=vhrao#icloud.com>, cached=0, nameComponents=viswanatha, userID=<CKRecordID: 0x283c6f940; recordName=__defaultOwner__, zoneID=_defaultZone:__defaultOwner__>, contactIdentifiers={\n items = (\n );\n}>>"
), allowsReadOnlyParticipantsToSeeEachOther=YES, publicPermission=none, recordChangeTag=2z, rootRecordID=<CKRecordID: 0x283c39360; recordName=645B675E-121F-4DC8-B86D-8968C8DE7B1C-9651-00000ED7A0D0E95D, zoneID=userProfileZone:__defaultOwner__>, routingKey=0N9, recordID=Share-967C18F4-43C4-4958-9D40-6D890DD205AD:(userProfileZone:__defaultOwner__), recordType=cloudkit.share, etag=2z> and nil
record completion <CKRecord: 0x10bc05ac0; recordID=645B675E-121F-4DC8-B86D-8968C8DE7B1C-9651-00000ED7A0D0E95D:(userProfileZone:__defaultOwner__), recordChangeTag=30, values={
asOfDate = "2020-08-01 20:26:44 +0000";
latitude = "29.9288104125185";
locationId = "1D2A93A8-A22C-4B2A-9EC6-86F646667F3E-8282-00000CF78F38B1DB";
locationType = "Household User";
longitude = "-95.6080147578347";
profileImage = "<CKAsset: 0x10bc05f60; referenceSignature=<01ebb50c 4bd0e618 bb0f4486 b486145b 30f22689 83>, uploadRank=0, path=/private~/Library/Caches/CloudKit/0fce42f4be876f65546aa1b4549b3658e9291963/Assets/B21AB25E-C07A-4D65-9238-61A17B3E6372.01b1f7f738f239ee006815df2bb2896fade0f08229, size=34656, UUID=B21AB25E-C07A-4D65-9238-61A17B3E6372, signature=<01b1f7f7 38f239ee 006815df 2bb2896f ade0f082 29>, wrappedAssetKey=<24 bytes>>";
userType = "Consumer";
}, share=<CKReference: 0x283c38ae0; recordID=<CKRecordID: 0x283c390c0; recordName=Share-967C18F4-43C4-4958-9D40-6D890DD205AD, zoneID=userProfileZone:__defaultOwner__>>, recordType=infrastructure> and nil
Then I fetch RecordZones
func fetchRecordZones(completion: #escaping (CKRecordZoneID?, Error?) -> Void) {
var fetchedRecordZones: [CKRecordZoneID : CKRecordZone]? = nil
let fetchZonesOperation = CKFetchRecordZonesOperation.fetchAllRecordZonesOperation()
fetchZonesOperation.fetchRecordZonesCompletionBlock = { (recordZones: [CKRecordZoneID : CKRecordZone]?, error: Error?) -> Void in
guard error == nil else {
completion(nil, error)
return
}
if let recordZones = recordZones {
fetchedRecordZones = recordZones
for recordID in recordZones.keys {
print(recordID.zoneName)
if (recordID.zoneName == Cloud.SharedZone.UserProfile.ZoneName) {
completion(recordID, nil)
}
}
}
completion(nil, nil)
}
fetchZonesOperation.qualityOfService = .utility
self.sharedDB?.add(fetchZonesOperation)
}
I get no recordZones
I go to coud Kit and look at the shared database and fetch zones with fetch with change Token checkbox enabled I get name: userProfileZone owner record name:_9d4825db9b0aa911655e420ec0016129
Looks like it has a zone in shared database. At least seems like, so why am I not getting zones from shared database?
//Sharing code
var lookupInfos = [CKUserIdentity.LookupInfo]()
let creatorID = rootRecord.creatorUserRecordID
self.defaultContainer?.discoverUserIdentity(withUserRecordID: creatorID!) { [weak self] (userIdentity, error) in
guard error == nil else {
if let ckerror = error as? CKError {
self!.aErrorHandler.handleCkError(ckerror: ckerror)
}
completion(false, error)
return
}
if let userIdentity = userIdentity {
lookupInfos.append(userIdentity.lookupInfo!)
let share = CKShare(rootRecord: rootRecord)
share[CKShareTitleKey] = "Infrastructure" as CKRecordValue
//share[CKShareThumbnailImageDataKey] = shoppingListThumbnail as CKRecordValue
share[CKShareTypeKey] = "com.nr2r.infrastructure" as CKRecordValue
if let lookupInfo = userIdentity.lookupInfo {
let op: CKFetchShareParticipantsOperation = CKFetchShareParticipantsOperation(userIdentityLookupInfos: [lookupInfo])
op.fetchShareParticipantsCompletionBlock = { error in
if let error = error {
print("error: ", error)
}
}
op.shareParticipantFetchedBlock = { participant in
participant.permission = .readWrite
share.addParticipant(participant)
let modOp: CKModifyRecordsOperation = CKModifyRecordsOperation(recordsToSave: [rootRecord, share], recordIDsToDelete: nil)
modOp.savePolicy = .ifServerRecordUnchanged
modOp.perRecordCompletionBlock = {record, error in
print("record completion \(record) and \(String(describing: error))")
}
modOp.modifyRecordsCompletionBlock = {records, recordIDs, error in
guard let ckrecords: [CKRecord] = records, let record: CKRecord = ckrecords.first, error == nil else {
print("error in modifying the records " + error!.localizedDescription)
completion(false, error)
return
}
if let records = records {
for record in records {
print ("recordType: \(record.recordType)")
if (record.recordType == "cloudkit.share") {
self!.sharedCKRecordZoneID = record.recordID.zoneID
}
print ("recordName: \(record.recordID.recordName)")
print ("zoneID: \(record.recordID.zoneID.zoneName)")
print ("zoneID: \(record.recordID.zoneID.ownerName)")
}
}
if let anURL = share.url {
print("share url \(String(describing: share.url))")
completion(true, nil)
}
}
self?.privateDB?.add(modOp)
}
self?.defaultContainer?.add(op)
}
} else {
completion(false, nil)
}
}
More edits to show how to retrieve shared record:
let op = CKFetchShareMetadataOperation(shareURLs: [aURL])
op.perShareMetadataBlock = { shareURL, shareMetadata, error in
if let shareMetadata = shareMetadata {
if shareMetadata.participantStatus == .accepted {
let query = CKQuery(recordType: Cloud.Entity.Infrastructure, predicate: NSPredicate(format: "TRUEPREDICATE", argumentArray: nil))
let zone = CKRecordZoneID(zoneName: Cloud.PrivateZone.UserProfile.ZoneName, ownerName: (shareMetadata.ownerIdentity.userRecordID?.recordName)!)
self.sharedDB?.perform(query, inZoneWith: zone, completionHandler: { (records, error) in
if let ckerror = error as? CKError {
self.aErrorHandler.handleCkError(ckerror: ckerror)
completion(nil, error)
} else if let records = records, let firstRecord = records.first {
completion(firstRecord, nil)
}
})
}
}
Fetching shared database zones return zero
self.sharedDB?.fetchAllRecordZones(completionHandler: { (ckrecordZones, error) in
guard error == nil else {
if let ckError = error as? CKError {
self.aErrorHandler.handleCkError(ckerror: ckError)
}
completion (nil, error)
return
}
if let recordZones = ckrecordZones {
for i in 0 ..< recordZones.count{
// find the zone you want to query
if recordZones[i].zoneID.zoneName == Cloud.SharedZone.UserProfile.ZoneName {
completion (recordZones[i].zoneID, nil)
}
}
}
completion (nil, nil)
})

CloudKit how to modify existing record (swift 3)

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)

Swift - some mp3 file metadata return nil

I have code like below. For some file I got metadata like artist, title and other without any problem. For other files metadata list is nil but when I check metadata in editor like Tagger - title and other metadata exists. Furthermore when I change metadata in external editor for at least one key - my code starts work properly.
Could someone explain me where I make mistake ?
static func getBookInCatalog(url: URL) -> Book {
let book = Book(url: url)
let isDir: ObjCBool = false
var directoryContents = [URL]()
var totalTime: CMTime?
var size: UInt64 = 0
var chapters:Int = 0
do {
directoryContents = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil, options: [])
} catch let error as NSError {
print(error.localizedDescription)
return book
}
for item in directoryContents {
if !isDir.boolValue {
let result = appDelegate.fileTypes.filter { $0==item.pathExtension.lowercased() }
if !result.isEmpty {
chapters += 1
let fileSize = (try! FileManager.default.attributesOfItem(atPath: item.path)[FileAttributeKey.size] as! NSNumber).uint64Value
size += fileSize
let playerItem = AVPlayerItem(url: item)
let metadataList = playerItem.asset.commonMetadata
let asset = AVURLAsset(url: item, options: nil)
let audioDuration = asset.duration
if let _ = totalTime {
totalTime = totalTime! + audioDuration
} else {
totalTime = audioDuration
}
for metadata in metadataList {
guard let key = metadata.commonKey, let value = metadata.value else{
continue
}
switch key {
case "albumName":
if book.title == nil || book.title == "" {
book.title = (value as? String)!
}
case "artist":
if book.author == nil || book.author == "" {
book.author = (value as? String)!
}
case "artwork" where value is NSData:
if book.image == nil {
book.image = UIImage(data: (value as! NSData) as Data)
}
default:
continue
}
}
}
}
}
if let imageInsideCatalog = getImageFromFolder(url: url){
book.image = imageInsideCatalog
}
if book.title == nil {
book.title = url.deletingPathExtension().lastPathComponent
}
book.chapters = chapters
book.totalTime = totalTime
book.size = size
return book
}
MP3 meta data "standards" have gone through several major iterations over the years (see http://id3.org) . Your editor may be able to read older formats (that AVURLAsset may not support) and save them using the latest/current standard which would make them compatible after any change.