使用 Cloudkit 个资源作为 UIimage

Using Cloudkit Assets as a UIimage

我将图像作为资产保存在 CloudKit 中。每条记录还有其他属性。我可以收集记录并使用其他属性,但我无法在我的 ImageView 中使用该资产。我是 Swift 编程新手,因此我收到的错误没有任何意义。

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)
        }
    }

我得到的错误是在这一行:

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

它说:

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

我试图从主线程中删除它,但我收到了同样的错误。

也许问题在于 CKAsset 记录为零,但您强制 具有 fileURL 值。

尝试使用此代码段获取 CloudKit 图像

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