我试图保存和载入图像,并从文件目录,但是我writeImageToPath
函数打印以下错误控制台,并说该文件不存在。
安慰
写图像目录
文件存在写入图像
错误写入图像目录文件不存在 - 文件:///用户/用户/库/开发商/ CoreSimulator /设备/ 70EAC77D-9F3C-4AFC-8CCA-A7B9B895BDE6 /数据/集装箱/数据/应用/ DDAF2EBD-5DDA- 4EA6-95D3-6785B74A0B09 /文件/上传/ http://i.annihil.us/u/prod/marvel/i/mg/a/f0/5202887448860 - 可供使用写入图像错误写入图像:错误域= NSCocoaErrorDomain代码= 4“文件‘5202887448860’不存在”。的UserInfo = {NSFilePath = /用户/用户/资源库/开发商/ CoreSimulator /设备/ 70EAC77D-9F3C-4AFC-8CCA-A7B9B895BDE6 /数据/容器/数据/应用/ DDAF2EBD-5DDA-4EA6-95D3-6785B74A0B09 /文档/上传/ http://i.annihil.us/u/prod/marvel/i/mg/a/f0/5202887448860,NSUnderlyingError = 0x600003b04ab0 {错误域= NSPOSIXErrorDomain代码= 2 “没有这样的文件或目录”}}
这里是我的代码,我不知道我要去的地方错了
// The images are loaded from the web and displayed in the cell.imageView.image
if let thumbnail = product["thumbnail"] as? [String: Any],
let path = thumbnail["path"] as? String,
let fileExtension = thumbnail["extension"] as? String {
//Save image to directory
if image != nil {
writeImageToPath(path, image: image!)
}
}
// Write image to directory
func writeImageToPath(_ path: String, image: UIImage) {
print("Write image to directory")
let uploadURL = URL.createFolder(folderName: "upload")!.appendingPathComponent(path)
if !FileManager.default.fileExists(atPath: uploadURL.path) {
print("File does NOT exist -- \(uploadURL) -- is available for use")
let uploadURL = URL.createFolder(folderName: "upload")!.appendingPathComponent(path)
if let data = UIImageJPEGRepresentation(image, 0.9) {
do {
print("Write image")
try data.write(to: uploadURL)
}
catch {
print("Error Writing Image: \(error)")
}
} else {
print("Image is nil")
}
} else {
print("This file exists -- something is already placed at this location")
}
}
// load image from directory
func loadImageFromPath(_ path: String) -> UIImage? {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let folderURL = documentsURL.appendingPathComponent("upload")
let fileURL = folderURL.appendingPathComponent(path)
if FileManager.default.fileExists(atPath: fileURL.path) {
//Get Image And upload in server
print("fileURL.path \(fileURL.path)")
do{
let data = try Data.init(contentsOf: fileURL)
let image = UIImage(data: data)
return image
}catch{
print("error getting image")
}
} else {
print("No image in directory")
}
return nil
}
extension URL {
static func createFolder(folderName: String) -> URL? {
let fileManager = FileManager.default
// Get document directory for device, this should succeed
if let documentDirectory = fileManager.urls(for: .documentDirectory,
in: .userDomainMask).first {
// Construct a URL with desired folder name
let folderURL = documentDirectory.appendingPathComponent(folderName)
// If folder URL does not exist, create it
if !fileManager.fileExists(atPath: folderURL.path) {
do {
// Attempt to create folder
try fileManager.createDirectory(atPath: folderURL.path,
withIntermediateDirectories: true,
attributes: nil)
} catch {
// Creation failed. Print error & return nil
print(error.localizedDescription)
return nil
}
}
// Folder either exists, or was created. Return URL
return folderURL
}
// Will only be called if document directory not found
return nil
}
}
我怎样才能正确保存并从目录中加载图像?
class MyImageClass {
func writeImageToPath(_ path:String, image:UIImage) {
let uploadURL = URL.createFolder(folderName: "upload")!.appendingPathComponent(path)
if !FileManager.default.fileExists(atPath: uploadURL.path) {
print("File does NOT exist -- \(uploadURL) -- is available for use")
let data = image.jpegData(compressionQuality: 0.9)
do {
print("Write image")
try data!.write(to: uploadURL)
}
catch {
print("Error Writing Image: \(error)")
}
}
else {
print("This file exists -- something is already placed at this location")
}
}
}
extension URL {
static func createFolder(folderName: String) -> URL? {
let fileManager = FileManager.default
// Get document directory for device, this should succeed
if let documentDirectory = fileManager.urls(for: .documentDirectory,
in: .userDomainMask).first {
// Construct a URL with desired folder name
let folderURL = documentDirectory.appendingPathComponent(folderName)
// If folder URL does not exist, create it
if !fileManager.fileExists(atPath: folderURL.path) {
do {
// Attempt to create folder
try fileManager.createDirectory(atPath: folderURL.path,
withIntermediateDirectories: true,
attributes: nil)
} catch {
// Creation failed. Print error & return nil
print(error.localizedDescription)
return nil
}
}
// Folder either exists, or was created. Return URL
return folderURL
}
// Will only be called if document directory not found
return nil
}
}
var saving = MyImageClass()
saving.writeImageToPath("whereIWantToSaveTheImageTo", image: UIImage(named: "myImage"))
参考Create Directory in Swift 3.0
如果成像的工作,但是,这并创建一个名为“上传”文件夹,每次都可以把它叫做我没有测试。扩展有一个名为createFolder
方法,它返回无论你怎么称呼一个文件夹,并创建它,如果它已不存在。我们只要检查该文件夹中指定的路径,那么如果它是可用的,我们可以写它。我也只是改写了writeImageToPath
部分。
注意:
在操场上测试了这个...
结果如下:
File does NOT exist -- file:///var/folders/vs/nlj__xh93vs0f8wzcgksh_zh0000gn/T/com.apple.dt.Xcode.pg/containers/com.apple.dt.playground.stub.iOS_Simulator.MyPlayground-67A67A07-51FF-4DF4-BE80-02E7FDAFA1CA/Documents/upload/whereIWantToSaveTheImageTo -- is available for use
Write image
下面是我如何图像保存到一个名为“屏幕截图”文件夹中。我试图保持它明确的,因为我可以。
func saveImageToDocumentDirectory(image: UIImage) {
var objCBool: ObjCBool = true
let mainPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0];
let folderPath = mainPath + "/Screenshots/"
let isExist = FileManager.default.fileExists(atPath: folderPath, isDirectory: &objCBool)
if !isExist {
do {
try FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
} catch {
print(error)
}
}
let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let imageName = "\(fileName).png"
let imageUrl = documentDirectory.appendingPathComponent("Screenshots/\(imageName)")
if let data = image.jpegData(compressionQuality: 1.0){
do {
try data.write(to: imageUrl)
} catch {
print("error saving", error)
}
}
}
这是我的加载文件夹中存储的图像
func loadImageFromDocumentDirectory(nameOfImage : String) -> UIImage {
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first{
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("Screenshots/\(nameOfImage)")
guard let image = UIImage(contentsOfFile: imageURL.path) else { return UIImage.init(named: "fulcrumPlaceholder")!}
return image
}
return UIImage.init(named: "imageDefaultPlaceholder")!
}
路径名是错的正确的路径名来代替这个函数调用
writeImageToPath("http://i.annihil.us/u/prod/marvel/i/mg/b/70/4c0035adc7d3a", image: image)
至
writeImageToPath("4c0035adc7d3a", image: image)