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

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

我收到的错误是:

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

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

我正在使用 Swift 3.0

最佳答案

当我将我的旧 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(返回 void)行。这是多余的。让我知道这是否有效。

关于swift - 将记录保存到 CloudKit 时应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41906043/

相关文章:

swift - 为什么我不能快速在 CKRecord 对象上使用下标?

ios - CKModifyRecordsOperation 中的 clientChangeTokenData 是什么?

swift - Swift AlamoFire 中的 SSL 固定

ios - Amazon Rekognition 从流视频中检测名人

Swift 特殊闭包语法

swift - Moya - 使用 NSOperation 链式请求

php - 如何使用 CloudKit Web 服务创建 CKReference?

ios - CKQueryOperation 可见性、取消和超时可能性

android - 我可以在 Android 或基于 Web 的应用程序上使用 CloudKit 吗?

ios - 实时获取 Apple Watch 心率变异性 SDNN?