2017-01-28 4 views
1

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

これがオンになっています2番目に最後の行} as! (CKRecord?, Error?) -> Void)

私は私がスウィフト3に私の古いスウィフト2.xのプロジェクトを変換するとき、彼らはCloudKit完了ハンドラを取るこれと同じ問題を抱えていた、との代わりに、スウィフト3に変換しましたスウィフト3.0

+0

クラッシュの原因は何ですか? – Pierce

+0

@Pierce '}と言う行は! (CKRecord?、Error?)?> Void) 'を返します。これを質問に追加します。 –

+0

私はそれが何であるかを知っています - >私は答えを投稿します。あなたのプロジェクトをSwiftの古いバージョンからSwift 3に変換した後にこれが起こりましたか? – Pierce

答えて

1

を使用しています - それは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)") 
    } 
} 

は、基本的にはあなただけErrorNSErrorを変更する必要があり、あなたは-> void(リターンのボイド)のラインを取り除くことができます。それは余分です。そのことが分かれば教えてください。

+0

パーフェクト! Pierceに感謝します。 –

+0

@AnnabelleSykes - 確かなこと...運が良かった! – Pierce