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)
}
Related
I am trying to write to a plist in xcode. What I've written works, except the plist file doesn't change. I've tried a few different implementations of this, and reaching the same result.
Here is the code:
func saveGameData() {
let BedroomFloorKey = "BedroomFloor"
let BedroomWallKey = "BedroomWall"
var bedroomFloorID: AnyObject = 101 as AnyObject
var bedroomWallID: AnyObject = 101 as AnyObject
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
let documentsDirectory = paths.object(at: 0) as! NSString
let path = documentsDirectory.appendingPathComponent("room.plist")
print("PATH", path)
let dict: NSMutableDictionary = ["XInitializerItem": "DoNotEverChangeMe"]
//saving values
dict.setObject(bedroomFloorID, forKey: BedroomFloorKey as NSCopying)
dict.setObject(bedroomWallID, forKey: BedroomWallKey as NSCopying)
//...
//writing to GameData.plist
dict.write(toFile: path, atomically: false)
let resultDictionary = NSMutableDictionary(contentsOfFile: path)
print("Saved GameData.plist file is --> \(resultDictionary?.description ?? "")")
}
My plist is in the main directory of my xcode project, same folder as were the ViewController is.
Thanks
You cannot write into the application bundle, for obvious reasons the bundle is read-only.
Your code writes the plist into the Documents directory in the container of the application. If you have a default Property List file in the application bundle copy it on the first launch of the app into the Documents directory.
However the code looks like a ugly literal translation of Objective-C code. This is a native Swift version
func saveGameData() throws {
let bedroomFloorKey = "BedroomFloor"
let bedroomWallKey = "BedroomWall"
let bedroomFloorID = 101
let bedroomWallID = 101
let documentsDirectory = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let url = documentsDirectory.appendingPathComponent("room.plist")
print("PATH", url)
var dict : [String:Any] = ["XInitializerItem": "DoNotEverChangeMe"]
//saving values
dict[bedroomFloorKey] = bedroomFloorID
dict[bedroomWallKey] = bedroomWallID
//...
//writing to GameData.plist
let data = try PropertyListSerialization.data(fromPropertyList: dict, format: .xml, options: 0)
try data.write(to: url)
print("Saved GameData.plist file is --> \(dict)")
}
There is no need to reread the data. If no error is thrown the plist has been written successfully.
You create a plist file inside documents
let path = documentsDirectory.appendingPathComponent("room.plist")
which isn't same as the file located in your main bundle ( same level as ViewController.swift ) which won't accept any write as bundle is signed with the app and can't accept any change
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)
}
Trying to create a nested directory within Application Support and it's failing. The error message I get is "You don’t have permission to save the file 'folder1' in the folder 'testApp'.
let path = getApplicationSupportDirectory()
let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as! String
let folder = path.appendingPathComponent("\(appName)/folder1", isDirectory: true)
print("[ERR]: Folder location: \(folder.relativePath)")
if !FileManager.default.fileExists(atPath: folder.relativePath) {
do {
try FileManager.default.createDirectory(atPath: folder.relativeString, withIntermediateDirectories: true, attributes: nil)
} catch {
print("[ERR]: \(error.localizedDescription)")
}
}
Folder location outputs the correct location and it appears to create the first directory within "appName".
Please try this code, it's supposed to work.
It uses the API of FileManager to create the Application Support folder if it does not exist.
do {
let applicationSupportFolderURL = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as! String
let folder = applicationSupportFolderURL.appendingPathComponent("\(appName)/folder1", isDirectory: true)
print("[ERR]: Folder location: \(folder.path)")
if !FileManager.default.fileExists(atPath: folder.path) {
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true, attributes: nil)
}
} catch { print(error) }
I am using Swift 4, Xcode 9, and development target iOS 11.0.
I am trying to append a custom folder (MyFolder) to the path variable.
let outputFilePath = (NSTemporaryDirectory() as NSString).appending("MyFolder").appendingPathComponent((outputFileName as NSString).appendingPathExtension("mov")!)
But builder is giving error message:
appendingPathComponent' is unavailable: Use appendingPathComponent on URL instead.
I know, I am doing some silly mistake. Can you kindly help me in this?
Use this line
URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("MyFolder").appendingPathComponent(outputFileName).appendingPathExtension("mov")
instead of
(NSTemporaryDirectory() as NSString).appending("MyFolder").appendingPathComponent((outputFileName as NSString).appendingPathExtension("mov")!)
This will return you a url and use url.Path to get its path in string .
Hope this helps you.
Check below code for reference in document Directory
class func getDocumentsDirectory() -> URL {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let dataPath = documentsDirectory.appendingPathComponent("FolderName")
do {
try FileManager.default.createDirectory(atPath: dataPath.path, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
print("Error creating directory: \(error.localizedDescription)")
}
return dataPath
}
For Appending Files in Folder You can use this
//name for file to be added
let uuid = UUID().uuidString
// storing a Audio File in Directory
let audioFilename = getDocumentsDirectory().appendingPathComponent("\(uuid).m4a")
To get Names of Files Available in the respected Folder created
//This function returns a Array with file names Available
class func getListOfRecordingsAvailable() -> [String] {
var fileNameArray = [String]()
let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let myFilesPath = documentDirectoryPath.appending("/FolderName")
let files = FileManager.default.enumerator(atPath: myFilesPath)
while let file = files?.nextObject() {
//myfilesPath - Path
//file - fileName
fileNameArray.append(file as! String)
}
print(fileNameArray)
return fileNameArray
}
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.