How to Create Separate Folder in iOS swift 3 - ios

I am implementing an native iOS app. I am capturing images and videos by using the custom camera and stored into Photos in iPhone but I need to save in seperate single folder for images and videos. And also I need to set a password for that folder through my App.Can anyone guide me for do this task?

var paths: [Any] = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let docDirectory: String = paths[0] as? String ?? ""
// Get documents folder
let dataPath: String = URL(fileURLWithPath: docDirectory).appendingPathComponent("/yourFolder").absoluteString
if !FileManager.default.fileExists(atPath: dataPath) {
try? FileManager.default.createDirectory(atPath: dataPath, withIntermediateDirectories: false, attributes: nil)
}

Related

How to use folders in swift not visible to users?

My app receives a Json file, i need to store this json for reading this and next I've read i need to remove that. How I can storage this file in safety mode? I don't want use a "normal folder" like download, but i want to use a internal folder in my app, is possible ? And if is not possible to use my internal folder, how i can storage my file in safaty mode on ios ?
Well the most popular option to save a file in iOS is saving in document directory of the application.
A document directory is a directory where you can save all possible files and folders what you want, and the files are completely safe from other applications, meaning, iOS doesn't permit any application to write in other's document directory. Moreover, users won't find the directory as like android.
To save a file in the document directory, for example an image file
let fileManager = FileManager.default
do {
let documentDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create:false)
let fileURL = documentDirectory.appendingPathComponent(name)
let image = #imageLiteral(resourceName: "Notifications")
if let imageData = image.jpegData(compressionQuality: 0.5) {
try imageData.write(to: fileURL)
return true
}
} catch {
print(error)
}
to remove the file from document directory
let fileManager = FileManager.default
do {
let documentDirectoryURL = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let fileURLs = try fileManager.contentsOfDirectory(at: documentDirectoryURL, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
for url in fileURLs {
try fileManager.removeItem(at: url)
}
} catch {
print(error)
}

How to store location of selected video from PhotoLibrary

When selecting a video from the Photo Library, iOS compresses the video and stores it in the tmp/ folder. That location is returned as the '.mediaURL' and is used to load the video into an AVPlayer. I am trying to save the location of the selected video so it can be played back later, but I found that the tmp/ url is cleared out at some point after closing the app and reopening it. For music, I can store the 'persistentID' to retrieve the songs later. I have not been able to find a good way to persist the location of the originally selected video so it can be replayed later without having to select it again during the current session. Looking for suggestions.
I am using Swift 5 for iOS.
Thanks...
When you use imagePicker to select a video from gallery , you need to copy it someWhere say inside the documents folder to be able to persistently reference it when you open the app again
This is the solution I found:
To save the selected video:
func saveVideoToDirectory(videoUrl: NSURL) {
let videoData = NSData(contentsOf: videoUrl as URL)
let path = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let newPath = path.appendingPathComponent("/backgroundVideo.mp4")
do {
try videoData?.write(to: newPath)
let movieData = NSKeyedArchiver.archivedData(withRootObject: newPath)
UserDefaults.standard.set(movieData, forKey: "movie")
//print("movie url: ", newPath)
} catch {
print(error)
}
}
to retrieve the video:
let movieData = UserDefaults.standard.object(forKey: "movie") as? Data
let movieUrl = NSKeyedUnarchiver.unarchiveObject(with: data) as! URL
//search for current documents path
let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let videoUrl = URL(fileURLWithPath: docPath.appendingFormat("/backgroundVideo.mp4"))
let playerItem = AVPlayerItem(url: videoUrl as URL)

Secure Folder in iOS swift3

I am creating custom folder in iPhone device by using my native iOS app. It is creating successfully.But I want to set a password for that Folder for securing Folder's data. How can I set the password for that folder in iOS swift?
var paths: [Any] = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory: String = paths[0] as? String ?? ""
// Get documents folder
let dataPath: String = URL(fileURLWithPath: documentsDirectory).appendingPathComponent("/MyFolder").absoluteString
if !FileManager.default.fileExists(atPath: dataPath) {
try? FileManager.default.createDirectory(atPath: dataPath, withIntermediateDirectories: false, attributes: nil)
}

Storing and retrieving image using path to stored file as String

I'm using Realm and storing the file path to captured images as Strings. I want to retrieve them later for use in a tableView. Here's my code to store the path for each image:
func saveImage(imageName: String){
//create an instance of the FileManager
let fileManager = FileManager.default
//get the image path
thisImagePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(imageName)
//get the image taken with camera
let image = originalCapturedImage
//get the PNG data for this image
let data = UIImagePNGRepresentation(image!)
//store it in the document directory
fileManager.createFile(atPath: thisImagePath as String, contents: data, attributes: nil)
print("Picture path at assignment \n")
print(thisImagePath as Any)
}
And here's the code to retrieve the image:
...
var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsPath = paths[0] //Get the docs directory
let filePath = URL(fileURLWithPath: documentsPath).appendingPathComponent(item.picPath).path
let image = UIImage(contentsOfFile: filePath)
print("Picture path at retrieval \n")
print(item.picPath as Any)
cell.imageWell.image = image
cell.imageWell.clipsToBounds = true
return cell
}
Here's the comparison of the file path at runtime:
Picture path at assignment
/var/mobile/Containers/Data/Application/0E9CACAD-C6B3-4F6C-B0DB-72C43AC722E1/Documents/1535219147
...
...
Picture path at retrieval
/var/mobile/Containers/Data/Application/0E9CACAD-C6B3-4F6C-B0DB-72C43AC722E1/Documents/1535219147
The paths appear identical to me, yet no image appears. I've searched all over SO, and at one point came across a mention of the use of the URL for the file path. Somehow, I lost track of that entry and haven't been able to find it again.
Any help would be greatly appreciated!
You can try with below code for writing the image to the file instead of creating file with content. try? data.write(to: URL(fileURLWithPath: documentsPath))
You can also refer below code for saving image.
class func saveImageToFileWithDirectory(_ imageData:Data, fileName:String, folderName : String? = nil) {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
let documentsDirectory = paths.object(at: 0) as! NSString
let path = documentsDirectory.appendingPathComponent(folderName) as NSString
if !FileManager.default.fileExists(atPath: path as String) {
do {
try FileManager.default.createDirectory(atPath: path as String, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
print(error.localizedDescription);
}
}
let imagePath = path.appendingPathComponent(fileName)
if !FileManager.default.fileExists(atPath: imagePath as String) {
try? imageData.write(to: URL(fileURLWithPath: imagePath))
} }
Code for retrieving the image looks good. If you need help in that also, pls comment, I will post that also.
Hope this solves your issue.

Image is not existing in document directory if I will run the app again using Swift 3

I am saving a camera image into my document directory. I am creating a document directory in my util class. Here below is my code :-
//Get Document Directory Path
func getDirectoryPath() -> String {
let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("Phss")
return paths
}
//Create Directory
func createDirectory(){
let fileManager = FileManager.default
let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("Phss")
if !fileManager.fileExists(atPath: paths){
try! fileManager.createDirectory(atPath: paths, withIntermediateDirectories: true, attributes: nil)
}
else{
Helper.sharedInstance.Print("Already dictionary created." as AnyObject)
}
}
After that I am saving image by name and some value (docAddedTime) and storing the path(imagePath) in my core data DB.
func saveImageDocumentDirectory(imageData : Data, docName : String) -> String {
let fileManager = FileManager.default
let imagePAth = (getDirectoryPath() as NSString).appendingPathComponent("\(String(describing: docAddedTime!) + "_" + "\(String(describing: docName))").png")
fileManager.createFile(atPath: imagePAth, contents: imageData, attributes: nil)
return imagePAth
}.
I am fetching image by image path which is saved in my local core data DB.
let fileManager = FileManager.default
let imagePAth = doc!.docPath! //Core Data DB Path of image
if fileManager.fileExists(atPath: imagePAth) {
imgView.image = UIImage(contentsOfFile: imagePAth
}
The problem is first time I am able to fetch image and is showing in my imageView but after that I will run the app again and I am trying to fetch image by this imagePath which is stored in my core data DB then it's not giving that file exist at this path.
Image is present at same Path but showing is not exits. I am not sure why this is happening.
Each time you are building the app from Xcode, new folder is being created and files will be in the new folder.
Do not rebuild the app just close the app from simulator and start the app again from simulator itself.
Complete Path of your file will be like:
file:///Users/username/Library/Developer/CoreSimulator/Devices/4FA96815-521B-4D84-B5C7-10697DE1908B/data/Containers/Data/Application/54CC678C-7E96-4DB6-83CC-6ECB506DC9BF/Documents/tmp.png
On the next build:
Application/54CC678C-7E96-4DB6-83CC-6ECB506DC9BF/Documents/
will be changed as:
Application/3F3093C6-2140-473B-8F99-A717AF162CDE/Documents/
where 3F3093C6-2140-473B-8F99-A717AF162CDE is created by Xcode not you
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = URL(fileURLWithPath: paths).appendingPathComponent("fileName")
You can try the above snippet. This one don't create a directory though, I would suggest first try to fetch straight from Documents directory, once its a success then create a directory and then store it.Let me know the exact scenario. What is the value of the path showing when running for the next time.

Resources