0
我是Swift的新手,我試圖將圖片從手機(或互聯網)的圖庫保存到我的應用程序。我發現許多教程展示瞭如何查看圖像,但沒有如何將它保存到我的應用程序(我猜到我的資產文件夾)並在以後使用它。有人能讓我走向正確的方向嗎?將畫廊中的圖片保存到iOS應用程序
我是Swift的新手,我試圖將圖片從手機(或互聯網)的圖庫保存到我的應用程序。我發現許多教程展示瞭如何查看圖像,但沒有如何將它保存到我的應用程序(我猜到我的資產文件夾)並在以後使用它。有人能讓我走向正確的方向嗎?將畫廊中的圖片保存到iOS應用程序
func saveImage (image: UIImage, path: String) -> Bool{
let pngImageData = UIImagePNGRepresentation(image)
//let jpgImageData = UIImageJPEGRepresentation(image, 1.0) // if you want to save as JPEG
let result = pngImageData!.writeToFile(path, atomically: true)
return result
}
這裏是如何在以後使用的函數代碼:
saveImage(image, path: imagePath)
但是之前你可以保存或加載任何你要知道「路徑」你要使用。 我們需要三樣東西:
這裏是如何,我們要做到這一點:
func getDocumentsURL() -> NSURL {
let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
return documentsURL
}
func fileInDocumentsDirectory(filename: String) -> String {
let fileURL = getDocumentsURL().URLByAppendingPathComponent(filename)
return fileURL.path!
}
// Define the specific path, image name
let imagePath = fileInDocumentsDirectory(myImageName)
訪問更多:http://helpmecodeswift.com/image-manipulation/saving-loading-images
我認爲首先您需要決定要保存的位置。有很多選擇。 (1)不建議將圖像保存到PList,(2)核心數據是一個選項。這一切都涉及到將數據保存到應用程序,因此在關閉和再次打開數據後,數據仍然存在。即它被稱爲「持久性」。 – devim1
https://www.udemy.com與Rob Percival有一些關於如何使用Core Data的背景信息。一個好的起點。雖然他也涵蓋了很多其他的東西。祝你好運! – devim1