Save and Get Image from Document Directory in Swift ?
Every Apps have its own storage at Document directory. In Document directory user can store audio,video,image,pdf and others files without collide to the others apps. and you can also read and write data of particular apps of Document directory.
Document directory store the user data or file at path of apps. All files are store the folder of particular app. You can read apps data from the path of document directory.
Save Image At Document Directory :
Document directory store the user data or file at path of apps. All files are store the folder of particular app. You can read apps data from the path of document directory.
Save Image At Document Directory :
func saveImageDocumentDirectory(){
let fileManager = NSFileManager.defaultManager()
let paths = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString).stringByAppendingPathComponent("apple.jpg")
let image = UIImage(named: "apple.jpg")
print(paths)
let imageData = UIImageJPEGRepresentation(image!, 0.5)
fileManager.createFileAtPath(paths as String, contents: imageData, attributes: nil)
}
Get Document Directory Path : func getDirectoryPath() -> String {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = paths[0]
return documentsDirectory
}
Get Image from Document Directory : func getImage(){
let fileManager = NSFileManager.defaultManager()
let imagePAth = (self.getDirectoryPath() as NSString).stringByAppendingPathComponent("apple.jpg")
if fileManager.fileExistsAtPath(imagePAth){
self.imageView.image = UIImage(contentsOfFile: imagePAth)
}else{
print("No Image")
}
}
Create Directory : func createDirectory(){
let fileManager = NSFileManager.defaultManager()
let paths = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString).stringByAppendingPathComponent("customDirectory")
if !fileManager.fileExistsAtPath(paths){
try! fileManager.createDirectoryAtPath(paths, withIntermediateDirectories: true, attributes: nil)
}else{
print("Already dictionary created.")
}
}
Delete Directory :func deleteDirectory(){
let fileManager = NSFileManager.defaultManager()
let paths = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString).stringByAppendingPathComponent("customDirectory")
if fileManager.fileExistsAtPath(paths){
try! fileManager.removeItemAtPath(paths)
}else{
print("Something wronge.")
}
}
Save and Get Image from Document Directory in Swift ?
Reviewed by KIRIT MODI
on
03:33:00
Rating:
No comments: