title: Saving image and then loading it in Swift (iOS)
body: <p>I am saving an image using saveImage.</p>
  
  <pre><code>func saveImage (image: UIImage, path: String ) -&gt; Bool{
  
      let pngImageData = UIImagePNGRepresentation(image)
      //let jpgImageData = UIImageJPEGRepresentation(image, 1.0)   // if you want to save as JPEG
  
      print("!!!saving image at:  \(path)")
  
      let result = pngImageData!.writeToFile(path, atomically: true)
  
      return result
  }
  </code></pre>
  
  <h2>New info:</h2>
  
  <p>Saving file does not work properly ("[-] ERROR SAVING FILE" is printed)--</p>
  
  <pre><code>            // save your image here into Document Directory
          let res = saveImage(tempImage, path: fileInDocumentsDirectory("abc.png"))
          if(res == true){
              print ("[+] FILE SAVED")
          }else{
              print ("[-] ERROR SAVING FILE")
          }
  </code></pre>
  
  <p>Why doesn't the saveImage function save the image? Access rights? </p>
  
  <h2>Older info:</h2>
  
  <p>The debug info says: </p>
  
  <pre><code>!!!saving image at:  file:///var/mobile/Applications/BDB992FB-E378-4719-B7B7-E9A364EEE54B/Documents/tempImage
  </code></pre>
  
  <p>Then I retrieve this location using</p>
  
  <pre><code>fileInDocumentsDirectory("tempImage")
  </code></pre>
  
  <p>The result is correct. </p>
  
  <p>Then I am loading the file using this path</p>
  
  <pre><code>    let image = UIImage(contentsOfFile: path)
  
      if image == nil {
  
          print("missing image at: \(path)")
      }else{
          print("!!!IMAGE FOUND at: \(path)")
      }
  </code></pre>
  
  <p>The path is correct, but the message is "missing image at..". Is the file somehow inaccessible or not stored? What can be a reason for this behavior?</p>
  
  <p>I am testing this code on iphone 4 with ios 7 and iphone 5 with ios 7 simulator. </p>
  
  <p>Edit:
  1. The fileInDocumentsDirectory function</p>
  
  <pre><code>func fileInDocumentsDirectory(filename: String) -&gt; String {
  
      let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
      let fileURL = documentsURL.URLByAppendingPathComponent(filename).absoluteString
      return fileURL        
  }
  </code></pre>