swiftcloudkitckqueryckasset

Using Cloudkit Assets as a UIimage


I have images saved in CloudKit as an asset. There are other attributes for each record as well. I can gather the record and use the other attributes, but I'm unable to use the asset in my ImageView. I'm new to Swift programming, therefore the error I receive does not make any sense.

let container = CKContainer.default()
let publicDB = container.publicCloudDatabase    

let query1 = CKQuery(recordType: "movieArray", predicate: predicate2)
    publicDB.perform(query1, inZoneWith: nil) {(results:[CKRecord]?, error:Error?) in
        if error != nil {
            DispatchQueue.main.async {
                print("Cloud Query Error - Fetch Establishments: \(String(describing: error))")
            }
            return
        }
        for record in results! {
            DispatchQueue.main.async {
                let asset = record["myImageKey"] as? CKAsset
                let data = NSData(contentsOf: (asset?.fileURL)!)
                let image = UIImage(data: data! as Data)
                print("Test")
                self.detailImage.image = image
            }
            self.movieCast.text = record.object(forKey: "Actors") as? String
            self.detailDescriptionLabel.text = record.object(forKey: "Description") as? String
            let youLink = record.object(forKey: "youtubeTag") as! String
            self.loadYoutube(videoID: youLink)
        }
    }

The error I get is on this line:

let data = NSData(contentsOf: (asset?.fileURL)!)

it says:

Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1020527c4

I attempted to remove it from the main thread, but I receive the same error.


Solution

  • Maybe the problem is that the CKAsset record is nil, but you are forcing to have a fileURL value.

    Try to obtain CloudKit image with this snippet

    if let asset = record["myImageKey"] as? CKAsset,
       let data = try? Data(contentsOf: (asset.fileURL)),
       let image = UIImage(data: data)
    {
        self.detailImage.image = image
    }