Setting up NSFileManager on Array

My array is setup as follows:

  
 
var images = [UIImage]()

As i add images in the app to the array i would like to us NSFileManager to save and retrieve those files when opening the app again.

func saveImageDocumentDirectory(){  let fileManager = NSFileManager.defaultManager()
  
//Error below in Paths
let paths = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString).stringByAppendingPathComponent()
  
//Error below in setting the image constant
let image = UIImage(imageView.image)  
print(paths)  
let imageData = UIImageJPEGRepresentation(image!, 0.5) fileManager.createFileAtPath(paths as String, contents: imageData, attributes: nil)  }

Also the code for inserting the image into the collection view is as follows below

  
 
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {  
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageView", for: indexPath)  
if let imageView = cell.viewWithTag(1000) as? UIImageView {  imageView.image = images[indexPath.item]  } 
 return cell  } 
@objc func importPicture() {  
let picker = UIImagePickerController()  
picker.allowsEditing = true  
picker.delegate = self  
present(picker, animated: true)  } 
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {  
guard let image = info[UIImagePickerControllerEditedImage] as? UIImage else { return }  dismiss(animated: true)  
images.insert(image, at: 0)  collectionView?.reloadData()  }

Replies

You haven’t asked any questions here, so I’m going to throw out some random ideas and hope that they stick. If that doesn’t help, please post back with more details as to what the problem is.

First up, I encourage you to move away from file system paths and towards file system URLs. That’s the direction that Apple is heading. For example,

NSSearchPathForDirectoriesInDomains
has effectively been replaced by the
FileManager
method
url(for:in:appropriateFor:create:)
, which both returns a URL and is much nicer to call.
let docDir = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileURL = docDir.appendingPathComponent("***")

Second,

createFile(atPath:contents:attributes)
is rarely used these days. Rather, most folks call the
write(to:)
method on
Data
. This takes a file system URL, so it matches up well with the previous code.
try imageData.write(to: fileURL)

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"


WWDC runs Mon, 4 Jun through to Fri, 8 Jun. During that time all of DTS will be at the conference, helping folks out face-to-face.