Swift - The file path is unavailable except for first time use
<p>Below code is work. The images are saved successfully in document directory, but the problem is only first time the collectionViewController can load images with path successfully. I have to delete all images to store new images or it will show the error message </p>

<blockquote>
  <p>"fatal error: unexpectedly found nil while unwrapping an Optional
  value".</p>
</blockquote>

<p>Because the path is unavailable, <code>readnsdata = NSData(contentsOfFile: filepath)!</code> will cause error.</p>

<p>I have no idea why only the first time it can work.</p>

<blockquote>
  <p>path :
  "/var/mobile/Containers/Data/Application/29306029-BDCF-4BEA-93A6-D5626CBAAA90/Documents/x.jpg"</p>
</blockquote>

<pre><code>func writeNSDataToDisk(imageData:NSData){

    let myindex = imgPathArray.count
    let fileName = "\(self.imgPathArray.count)"
    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    let docs: String = paths[0] as String
    let filepath: String = (docs as NSString).stringByAppendingPathComponent("\(fileName).jpg")        
    let test = imageData.writeToFile(filepath, atomically: true)
    if test {
        self.imgPathArray.insert(filepath, atIndex: myindex)
        print("The picture \(fileName).jpg is been saved.")
        self.readORwriteList(true)//write list to txt file
    }
    print(self.imgPathArray)
}


func readNSDataFromDisk(fileIndex:Int) -&gt; NSData{
    let checkValidation = NSFileManager.defaultManager()
    var readnsdata = NSData()
    if (fileIndex &lt;= self.imgPathArray.count) {
        let filepath = self.imgPathArray[fileIndex]
        if (checkValidation.fileExistsAtPath(filepath)){
            print("File is available")
            print("load \(fileIndex).jpg,filepath is \(filepath)")
            readnsdata = NSData(contentsOfFile: filepath)!
            if readnsdata.length != 0 {
                getImageProperties(readnsdata)
            }
        }
        else{
            print("File is not available!!!")
        }
    }
    return readnsdata
}
</code></pre>

<hr>

<p>The solution to my problem : </p>

<p>Instead of storing absolute file path, I name the files in a regular way and search them by their name. There is no need to store path.</p>

<p>The URLs for the files are now constructed relative to the Documents directory URL every time the app is run. </p>

<p>Thanks</p>