1

I have string array of file names, which looks like this

["xBGEx.jpg", "OgJuM.jpg"]

This is images, which saved to documents directory. I try to create array of UIImages by appending full path in for look and then appending to array.

In my appDelegate I have code in didFinishLaunchingWithOptions it looks like

    var paths:[AnyObject] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    var documentsDirectory = paths[0] as? String
    self.documentsRoot = documentsDirectory! + "/"

Then, when Im in controller, which I need I do the following

var slider = ["xBGEx.jpg", "OgJuM.jpg"]
var UIImageArray = [UIImage]()

for element in imgArray {
        var path = "\(appDelegate.documentsRoot!)" + "\(element)"
        var obj:UIImage = UIImage(contentsOfFile: path)!
        UIImageArray.append(obj)
    }

imageArray = UIImageArray

but when I build I have nil error in the moment of appending enter image description here

What am I doing wrong ?

1
  • NSSearchPathForDirectoriesInDomains returns an non-optional [String], any casting and optional binding is not needed at all. Apart from that I recommend the URL related API of NSFilemanager and the designated methods to append path components. Commented Oct 22, 2015 at 10:40

1 Answer 1

2

Seems like the path doesn't lead to an image file. You should check if the file you found a path for really is an image and not force the cast with !

for element in imgArray {
    var path = "\(appDelegate.documentsRoot!)" + "\(element)"
    if let obj = UIImage(contentsOfFile: path) {
        UIImageArray.append(obj)
    }   
}

On another note PLEASE don't name your variables with a capital letter uiImageArray would be much better.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.