2016-09-20 31 views
2

我正在使用核心數據將url存儲到從imagepicker中獲取的圖像。如何在swift中將圖像寫入路徑3.0

到目前爲止,我有以下幾點:

let tempImage = info[UIImagePickerControllerOriginalImage] as? UIImage 

    let image = UIImageJPEGRepresentation(tempImage!, 0.2) 

    let path = try! FileManager.default.url(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask, appropriateFor: nil, create: false) 
    let imageName = UUID().uuidString + ".jpg" 

    let aPath = path.path 

    let imagePath = (aPath as NSString).appendingPathComponent(imageName) 

結果是現在我有一個路徑作爲字符串中的核心數據進行保存。 但是,如何將圖像寫入路徑? 我試圖用:

let result = image!.writeToFile(path, atomically: true) 

,但我得到一個錯誤說類型的數據的價值沒有成員將writeToFile。是否有另一種方法在3.0版本中完成?

感謝您的幫助。

+0

只需推動的,而不是將其轉換UIImageJPEGRepresentation,並再次將其保存 –

回答

9

在斯威夫特3,UIImageJPEGRepresentation創建Data而不是NSData。您可以使用write而不是writeToFile

您應該能夠使用:

image.write(to: URL(fileURLWithPath: path), options: .atomic) 

,並在path寫出你的圖像數據image到文件中。請注意,它使用URL而不是字符串文件路徑,並且options參數已更改。

+0

感謝這個原始文件,我結束了和我的代碼重寫了一點工作,但你指出我在正確的方向! :) – SwiftStarter

4

在Dylansturg的幫助下,

我能夠重寫我的代碼來工作。這裏是供將來參考代碼:

do { 
    let result = try image?.write(to: path, options: .atomic) 
} catch let error { 
    print(error) 
} 
+0

只需移動原始文件而不是將其轉換爲UIImageJPEGRepresentation並再次保存 –