将记录保存到CloudKit时,应用程序崩溃

时间:2017-01-28 03:31:34

标签: swift cloudkit

我正在使用CloudKit来保存用户输入的记录,但是我的应用程序崩溃了。

以下是我的代码:

func saveRecordToCloud(_ pinpoint:Details!) -> Void {
    // Prepare the record to save
    let record = CKRecord(recordType: "Details")
    record.setValue(pinpoint.title, forKey: "title")
    record.setValue(pinpoint.location, forKey: "location")
    record.setValue(pinpoint.date, forKey: "date")

    // Resize the image
    let originalImage = UIImage(data: pinpoint.image as Data)!
    let scalingFactor = (originalImage.size.width > 1024) ? 1024 / originalImage.size.width : 1.0
    let scaledImage = UIImage(data: pinpoint.image as Data, scale: scalingFactor)!

    // Write the image to local file for temporary use
    let imageFilePath = NSTemporaryDirectory() + pinpoint.title
    try? UIImageJPEGRepresentation(scaledImage, 0.8)?.write(to: URL(fileURLWithPath: imageFilePath), options: [.atomic])

    // Create image asset for upload
    let imageFileURL = URL(fileURLWithPath: imageFilePath)
    let imageAsset = CKAsset(fileURL: imageFileURL)
    record.setValue(imageAsset, forKey: "image")


    // Get the Public iCloud Database
    let publicDatabase = CKContainer.default().publicCloudDatabase

    // Save the record to iCloud
    publicDatabase.save(record, completionHandler: { (record:CKRecord?, error:NSError?) -> Void  in
        // Remove temp file
        do {
            try FileManager.default.removeItem(atPath: imageFilePath)

        } catch {
            print("Failed to save record to the cloud: \(error)")
        }
        } as! (CKRecord?, Error?) -> Void)
}

我收到的错误是:

  

主题1:EXC_BAD_INSTRUCTION(代码= EXC_I386_INVOP,子代码= 0x0)

这是第} as! (CKRecord?, Error?) -> Void)行,这是第二个。

我正在使用Swift 3.0

1 个答案:

答案 0 :(得分:1)

当我将旧的Swift 2.x项目转换为Swift 3时,我遇到了同样的问题。他们使用CloudKit完成处理程序,而不是将它们转换为Swift 3 - 它将它保留在Swift 2中,然后进行转换它作为Swift 3的CKCompletionHandler。它总是导致崩溃。从完成处理程序的末尾删除显示as! (CKRecord?, Error?) -> Void)的行。然后返回到您的实际完成处理程序并将其更改为如下所示:

publicDatabase.save(record, completionHandler: { (record:CKRecord?, error: Error?) in
    // Remove temp file
    do {
        try FileManager.default.removeItem(atPath: imageFilePath)

    } catch {
        print("Failed to save record to the cloud: \(error)")
    }
}

基本上你只需要将NSError更改为Error,就可以摆脱-> void(返回无效)行。这是多余的。如果有效,请告诉我。