2009-12-20 11 views

risposta

11

Questi metodi consentono di salvare e recuperare un'immagine dalla directory documenti su iPhone

+ (void)saveImage:(UIImage *)image withName:(NSString *)name { 
    NSData *data = UIImageJPEGRepresentation(image, 1.0); 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name]; 
    [fileManager createFileAtPath:fullPath contents:data attributes:nil]; 
} 

+ (UIImage *)loadImage:(NSString *)name { 
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];  
    UIImage *img = [UIImage imageWithContentsOfFile:fullPath]; 

    return img; 
} 
+0

Grazie per il tempo di risposta rapida. E risposta accurata. – Jaba

+4

E da dove proviene la directory Documenti? – jjxtra

+2

Dettagli sulla directory dei documenti qui http://stackoverflow.com/questions/6907381/what-is-the-documents-directory-nsdocumentdirectory/6907432#6907432 –

2

Inoltre, non si mai voglia di salvare nulla nella directory tmp reale che si desidera in giro dopo l'app si spegne. La directory tmp può essere eliminata dal sistema. Per definizione, esiste solo per contenere file secondari necessari solo quando l'app è in esecuzione.

I file che si desidera conservare devono sempre andare nella directory documents.

+0

Grazie, non lo sapevo – Jaba

1

La testato Swift Tweak per risposta selezionata:

class func saveImage(image: UIImage, withName name: String) { 
    let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String 
    var data: NSData = UIImageJPEGRepresentation(image, 1.0)! 
    var fileManager: NSFileManager = NSFileManager.defaultManager() 

    let fullPath = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent(name) 
    fileManager.createFileAtPath(fullPath.absoluteString, contents: data, attributes: nil) 
} 

class func loadImage(name: String) -> UIImage { 
    var fullPath: String = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent(name).absoluteString 
    var img:UIImage = UIImage(contentsOfFile: fullPath)! 
    return img 
} 
2

Testato Codice in rapida

//to get document directory path 
    func getDocumentDirectoryPath() -> NSString { 
     let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) 
     let documentsDirectory = paths[0] 
     return documentsDirectory 
    } 

chiamata utilizzando

if let data = UIImagePNGRepresentation(img) { 
    let filename = self.getDocumentDirectoryPath().stringByAppendingPathComponent("resizeImage.png") 
    data.writeToFile(filename, atomically: true) 
} 
2

Swift 3 xCode directory 8.2

Documenti ottenere:

func getDocumentDirectoryPath() -> NSString { 
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) 
    let documentsDirectory = paths[0] 
    return documentsDirectory as NSString 
} 

risparmio:

func saveImageToDocumentsDirectory(image: UIImage, withName: String) -> String? { 
    if let data = UIImagePNGRepresentation(image) { 
     let dirPath = getDocumentDirectoryPath() 
     let imageFileUrl = URL(fileURLWithPath: dirPath.appendingPathComponent(withName) as String) 
     do { 
      try data.write(to: imageFileUrl) 
      print("Successfully saved image at path: \(imageFileUrl)") 
      return imageFileUrl.absoluteString 
     } catch { 
      print("Error saving image: \(error)") 
     } 
    } 
    return nil 
} 

Caricamento:

func loadImageFromDocumentsDirectory(imageName: String) -> UIImage? { 
    let tempDirPath = getDocumentDirectoryPath() 
    let imageFilePath = tempDirPath.appendingPathComponent(imageName) 
    return UIImage(contentsOfFile:imageFilePath) 
} 

Esempio:

//TODO: pass your image to the actual method call here: 
let pathToSavedImage = saveImageToDocumentsDirectory(image: imageToSave, withName: "imageName.png") 
if (pathToSavedImage == nil) { 
    print("Failed to save image") 
} 

let image = loadImageFromDocumentsDirectory(imageName: "imageName.png") 
if image == nil { 
    print ("Failed to load image") 
} 
0

Swift 4 implementazione:

// saves an image, if save is successful, returns its URL on local storage, otherwise returns nil 
func saveImage(_ image: UIImage, name: String) -> URL? { 
    guard let imageData = UIImageJPEGRepresentation(image, 1) else { 
     return nil 
    } 
    do { 
     let imageURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(name) 
     try imageData.write(to: imageURL) 
     return imageURL 
    } catch { 
     return nil 
    } 
} 

// returns an image if there is one with the given name, otherwise returns nil 
func loadImage(withName name: String) -> UIImage? { 
    let imageURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(name) 
    return UIImage(contentsOfFile: imageURL.path) 
} 

esempio di utilizzo (supponendo che abbiamo un'immagine):

let image = UIImage(named: "milan") 

let url = saveImage(image, name: "savedMilan.jpg") 
print(">>> URL of saved image: \(url)") 

let reloadedImage = loadImage(withName: "savedMilan.jpg") 
print(">>> Reloaded image: \(reloadedImage)") 
Problemi correlati