将资产列表(数组)保存到特定的 CKRecord

Saving an Asset List (array) to specific CKRecord

我在 CloudKit 后端创建了一个 CKRecord 类型,其中包含一些与 class 相关的属性。

我有字符串属性、字节和资产列表 属性,因此存储一些图像(与单个记录相关的多个图像)。

现在我正在尝试存储一些图像,然后填充 属性,然后尝试将其保存到 CloudKit,但它不起作用。

代码如下:

var images_array = [CKAsset]()

// append the an image to the array 
images_array.append(CKAsset(fileURL: writeImage(image: selectedImage) as URL))


let record = CKRecord(recordType: recordName)
record["class_title"] = someString as CKRecordValue
record["class_body"]  = someString as CKRecordValue
record["images_array"] = images_array as CKRecordValue
saveRecord(record)

func saveRecord(_ xrecord: CKRecord) {
    let publicData = CKContainer.default().publicCloudDatabase
    let record: [CKRecord] = [xrecord] 
    let saveOperation = CKModifyRecordsOperation.init(recordsToSave: record, recordIDsToDelete: nil)

    saveOperation.perRecordCompletionBlock = {(record, error) -> Void in
        if (error != nil) {
            print("error")
        }
    }
    publicData.add(saveOperation)
}


func writeImage(image: UIImage) -> URL {
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let fileURL = NSURL(fileURLWithPath: documentsURL.absoluteString).appendingPathComponent(".jpg")

    if let imageData = image.lowestQualityJPEGNSData {
        do {
            try imageData.write(to: fileURL!)
        } catch {
            print("ERRO 001 = \(error.localizedDescription)")
        }
    }
    return fileURL!
}

extension UIImage {
    var uncompressedPNGData: Data?      { return UIImagePNGRepresentation(self)        }
    var highestQualityJPEGNSData: Data? { return UIImageJPEGRepresentation(self, 1.0)  }
    var highQualityJPEGNSData: Data?    { return UIImageJPEGRepresentation(self, 0.75) }
    var mediumQualityJPEGNSData: Data?  { return UIImageJPEGRepresentation(self, 0.5)  }
    var lowQualityJPEGNSData: Data?     { return UIImageJPEGRepresentation(self, 0.25) }
    var lowestQualityJPEGNSData:Data?   { return UIImageJPEGRepresentation(self, 0.0)  }
}

如果我只保存字符串,则一切正常,但对于图像,它不会保存记录。

我知道附加可能有任何问题,或者我必须以其他方式保存数组,或者我不应该将它保存为 CKRecordValue。

关于如何实现这一点,您有什么建议吗?

谢谢

您必须使用 CKAsset 的数组作为图像。

var imageUrls = [CKAsset]()

现在使用 for 循环获取所有图像。并保存图像的CKAsset。

for images in self.arrayImageSelected{

                  var myImage = UIImage()
                  if (images.isKindOfClass(PHAsset)){
                        let imageC = images as? PHAsset
                        myImage = self.getAssetThumbnail(imageC!)
                    }else if (images.isKindOfClass(UIImage)){
                        myImage = (images as? UIImage)!
                    }
                    let imagePath = self.storeImageAtDocumentDirectory(myImage, titleName: self.strTitle)
                    myPAth.append(imagePath)
                    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
                    let FbPath = paths.stringByAppendingString("/Custom")
                    let filePathToWrite = "\(FbPath)" + imagePath
                    let urls = NSURL(fileURLWithPath: filePathToWrite)
                    let imageAsset = CKAsset(fileURL: urls)
                    imageUrls.append(imageAsset)

                }

设置你的数组。

record.setObject(imageUrls, forKey: "images_array")

当您创建本地资产文件时,您应该使用原子写入选项。这将确保在 CloudKit 尝试上传资产之前完整写入文件。

这是我在Seam 3库中使用的资产文件创建函数:

fileprivate func createAsset(data: Data) -> CKAsset? {

    var returnAsset: CKAsset? = nil

    let tempStr = ProcessInfo.processInfo.globallyUniqueString
    let filename = "\(tempStr)_file.bin"        
    let baseURL = URL(fileURLWithPath: NSTemporaryDirectory())       
    let fileURL = baseURL.appendingPathComponent(filename, isDirectory: false)

    do {
        try data.write(to: fileURL, options: [.atomicWrite])         
        returnAsset = CKAsset(fileURL: fileURL)      
    } catch {
        print("Error creating asset: \(error)")
    }

    return returnAsset

}