After user choose image from the iPhone library with UIImagePickerController, I want to upload it to my server using ASIHTTPRequest library.
The easiest way I found is
Step 1: Get path for DocumentsDirectory
func fileInDocumentsDirectory(filename: String) -> String {
let documentsFolderPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as NSString
return documentsFolderPath.appendingPathComponent(filename)
}
Step 2: Save at the path with tempFileName
func saveImage(image: UIImage, path: String ) {
let pngImageData = UIImagePNGRepresentation(image)
do {
try pngImageData?.write(to: URL(fileURLWithPath: path), options: .atomic)
} catch {
print(error)
}
}
Step 3: Usage in imagePickerController function
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]){
if var image = info[UIImagePickerControllerOriginalImage] as? UIImage {// image asset
self.saveImage(image: image, path: fileInDocumentsDirectory(filename: "temp_dummy_image.png"))
}
Step 4 : To get the image when required
get the reference like this
let localfilepath = self.fileInDocumentsDirectory(filename: "temp_dummy_image.png")
Step 5: After using the image, to trash the temp image
func removeTempDummyImagefileInDocumentsDirectory(filename: String) {
let fileManager = FileManager.default
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! as NSURL
let documentsPath = documentsUrl.path
do {
if let documentPath = documentsPath
{
let fileNames = try fileManager.contentsOfDirectory(atPath: "\(documentPath)")
print("all files in cache: \(fileNames)")
for fileName in fileNames {
if (fileName.hasSuffix(".png"))
{
let filePathName = "\(documentPath)/\(fileName)"
try fileManager.removeItem(atPath: filePathName)
}
}
let files = try fileManager.contentsOfDirectory(atPath: "\(documentPath)")
print("all files in cache after deleting images: \(files)")
}
} catch {
print("Could not clear temp folder: \(error)")
}
}