如何从cloudkit接收图像?

时间:2015-04-09 20:14:00

标签: ios xcode swift icloud cloudkit

我使用此代码在icloud中存储图像,但是我使用什么代码来检索它并将其放在UIImageView中?我已经尝试了所有的东西,但它不会工作?

func SaveImageInCloud(ImageToSave: UIImage) {
    let newRecord:CKRecord = CKRecord(recordType: "ImageRecord")

    let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
    let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
    if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) {
        if paths.count > 0 {
            if let dirPath = paths[0] as? String {
                let writePath = dirPath.stringByAppendingPathComponent("Image2.png")
                UIImagePNGRepresentation(ImageToSave).writeToFile(writePath, atomically: true)

                var File : CKAsset?  = CKAsset(fileURL: NSURL(fileURLWithPath: writePath))
                newRecord.setValue(File, forKey: "Image")

            }
        }
    }

    if let database = self.privateDatabase {
        database.saveRecord(newRecord, completionHandler: { (record:CKRecord!, error:NSError! ) in
            if error != nil {
                NSLog(error.localizedDescription)
            } else {
                dispatch_async(dispatch_get_main_queue()) {
                    println("finished")
                }
            }
        })
    }

3 个答案:

答案 0 :(得分:10)

只需阅读您编写的CKRecord,即可通过读取关键图像获取CKAsset。你可以使用下面的代码获得UIImage。

var File : CKAsset? = record.objectForKey("Image")

func image() -> UIImage? {
    if let file = File {
        if let data = NSData(contentsOfURL: file.fileURL) {
            return UIImage(data: data)
        }
    }
    return nil
}

答案 1 :(得分:3)

下载CKAsset后,我们需要将CKAsset转换为UIImage。我们可以使用以下扩展名(Swift 4代码):

extension CKAsset {
    func toUIImage() -> UIImage? {
        if let data = NSData(contentsOf: self.fileURL) {
            return UIImage(data: data as Data)
        }
        return nil
    }
}

答案 2 :(得分:1)

您必须先找到要检索的特定ImageRecord的方法。假设您已经保存了ImageRecord的RecordID(您可以从saveRecord完成块中的记录中获取),您可以这样做:

if let database = privateDatabase {
    database.fetchRecordWithID(recordID, completionHandler: { (record, error) -> Void in
        guard let record = record else {
            print("Error retrieving record", error)
            return
        }

        guard let asset = record["Image"] as? CKAsset else {
            print("Image missing from record")
            return
        }

        guard let imageData = NSData(contentsOfURL: asset.fileURL) else {
            print("Invalid Image")
            return
        }

        let image = UIImage(data: imageData)
        imageView.image = image
    })
}

(虽然你肯定希望在那些print()的情况下进行一些错误处理)

如果你没有保存recordID(或者可能更好:recordID.recordName以便你可以在以后制作另一个CKRecordID),你需要一些其他方法来查找你正在寻找的记录。如果是这种情况,您希望使用CKDatabase performQuery(_:inZoneWithID:completionHandler:)方法进行调查。