How do I get the root directory of my iOS app? - ios

I am able to access the temporary directory for the current user of my iOS app, and I am able to access the bundle path as the following code shows:
print(FileManager.default.temporaryDirectory)
print(Bundle.main.bundlePath)
How do I access the root directory of the app for the current user? I need to create a cache directory or a Documents directory according to the instructions in the documentation in this link:
(https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html#//apple_ref/doc/uid/TP40010672-CH2-SW13)
The beta version of Xcode provides for a property that gives access to the home directory, but the latest release of Xcode does not.

let fileManager = FileManager.default
let pathOfDir = fileManager.currentDirectoryPath
print(pathOfDir)
This is use for get your root directory

func getDocumentsDirectory() -> URL
{
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
Please check this function for get root directory

I need to create a cache directory or a Documents directory according to the instructions in the documentation in this link:
You don't need to do this.
You access the Caches directory as follows:
try! FileManager.default.url(for: .cachesDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false)
.. and the documents directory as directed above.

Swift :
let homeDirectoryString = NSHomeDirectory()
let homeDirectoryURL = URL(fileURLWithPath: homeDirectoryString, isDirectory: true)
ObjC
NSString *homeDirectoryString = NSHomeDirectory();
NSURL *homeDirectoryURL = [NSURL fileURLWithPath:homeDirectoryString isDirectory:TRUE];

Related

User's document directory returning nil with FileManager

I'm trying to write a file locally but no success. When I try to get the user's document directory it returns nil and I believe this is why my file is not been stored.
Also, I have many doubts of what the "user's document directory" is supposed to mean. Is it the "Documents/" inside "iCloud Drive" or "on my phone". Should I be looking in another place instead of "Files" app? I'm using the iPhone simulator.
My code is designed as follow. documentFolderURL, fileURL and url are all nil when debugging.
let documentFolderURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last
let ext: String = type ?? "pdf"
let name = "extrato." + ext
let fileURL = documentFolderURL?.appendingPathComponent(name)
do {
if let url = fileURL {
try file.write(to: url, options: .atomic)
}
} catch {...}
Use the throwing API to get an error (there should be none)
do {
let documentFolderURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let ext: String = type ?? "pdf"
let fileURL = documentFolderURL.appendingPathComponent(name).appendingPathExtension(ext)
try file.write(to: fileURL, options: .atomic)
} catch { print(error) }
It seems that you are creating the file successfully, but you aren't looking for it in the right place.
You can navigate to the simulator's User Defaults folder by:
Print the file path of the simulator's documents directory. print(documentFolderURL) should print something like file:///Users/yourname/Library/Developer/CoreSimulator/Devices/8DAF542C-4B37-41D1-BA43-1D7C2A32E585/data/Containers/Data/Application/63545C94-56F5-3B11-B601-543801BE717A/Documents/
Copy the entire url EXCEPT the leading file:// (in other words, start with /User/yourname...
Open your macbook's Finder app, and press command + shift + g. This will allow you to...(drum roll please)...
Paste in the url to navigate to your simulator's documents directory.
Your file should be there :)

Where is a file stored in .documentDirectory?

I wrote a file in .documentDirectory in .userDomainMask:
do {
let fileManager = FileManager.default
let docs = try fileManager.url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil, create: false)
let path = docs.appendingPathComponent("myName.txt")
let data = "Hai...!".data(using: .utf8)!
fileManager.createFile(atPath: path.absoluteString, contents: data, attributes: nil)
} catch {
// handle error
}
I have not gotten any errors or exceptions. It runs perfectly. But I can't see that file. Where can I find that file?
just add in target -> info -> custom iOS Target properties
Application supports iTunes file sharing - YES
and you will be able to see the folder you saved a file in Files app on your simulator.
Otherwise use print(FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)) to get a path to folder using Finder

FileManager.default.fileExists says documents directory does not exist [duplicate]

This question already has answers here:
NSFileManager.defaultManager().fileExistsAtPath returns false instead of true
(2 answers)
Closed 4 years ago.
FileManager.default.contentsOfDirectory claims that the documents directory does not exist, even though it clearly does. I'm using Swift 4.2 on my actual iPhone SE running iOS 12.1.2
I am reading the contents of the downloads directory in my app using the following:
do {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let downloadedContents = try FileManager.default.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)
print(downloadedContents)
} catch {
print("Error while enumerating contents: \(error.localizedDescription)")
}
This prints the following, telling me that a file exists in the documents directory:
[file:///private/var/mobile/Containers/Data/Application/698F8D51-92AF-4BAB-A212-0A0982090550/Documents/example-file/]
(I moved the file there from the caches directory after downloading an in-app purchase, but I don't think that's relevant to this question).
Later in my code, I want to check if the file was downloaded. I'm using the following:
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let path = URL(fileURLWithPath: "example-file", relativeTo: documentsURL)
var isDir : ObjCBool = false
if FileManager.default.fileExists(atPath: path.standardizedFileURL.absoluteString, isDirectory: &isDir) {
if isDir.boolValue {
return true
} else {
return false // file exists but is not directory
}
} else {
return false // file does not exist at all
}
But this always returns false, even though contentsOfDirectory showed it exists.
While debugging, I also tried:
let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
po FileManager.default.fileExists(atPath: documentsURL.standardizedFileURL.absoluteString)
But this, too, returns false. Now I'm pretty sure I'm just using the fileExists methods incorrectly.
Can anyone spot what I'm doing wrong?
Turns out one should use documentsURL.path, instead of any sort of URL.
The path begins with /var/mobile... whereas the URLs begin with file:///var...

How to access the UserDefaults file folder on my ios application

I am would like to know how to access the Documents directory of my ios appplication. I have tried the following on xcode:
window > Devices and Simulators > [Select my device] > [select my application by name] > Show container.
The container comes back empty. I know that I have files stored because my application sigs me in automatically through the code in my app delegate:
let userId = UserDefaults.standard.string(forKey: "userId")
guard let id = userId else {
// <GO TO LOGIN PAGE return true>
}
// <GO TO HOME PAGE>
I am trying to verify that the following files exists as I have saved an image to the following url:
file:///var/mobile/Containers/Data/Application/6CEE9832-CE7B-4C31-9A62-F9F62D382C49/Documents/tempImage_wb.jpg
Your UserDefaults dictionary data is saved as a plist file, named as your app bundleIdentifier inside the Preferences directory inside your app Library directory:
let fileName = Bundle.main.bundleIdentifier!
let library = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first!
let preferences = library.appendingPathComponent("Preferences")
let userDefaultsPlistURL = preferences.appendingPathComponent(fileName).appendingPathExtension("plist")
print("Library directory:", userDefaultsPlistURL.path)
print("Preferences directory:", userDefaultsPlistURL.path)
print("UserDefaults plist file:", userDefaultsPlistURL.path)
if FileManager.default.fileExists(atPath: userDefaultsPlistURL.path) {
print("file found")
}
If you need to check the contents of your Documents or to locate this file in your computer simulator all you need to do is to open your Mac finder and use the File menu option Go > Go To Folder… and copy and paste your app preferences folder path that is printed in the console there.
let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let imageURL = documents.appendingPathComponent("tempImage_wb.jpg")
print("Documents directory:", imageURL.path)

Different path after appendingPathComponent(_:)

I am trying to access json files I copied to the ~/Documents folder.
When I check what files are available there, it has those files in an array with paths beginning with file:///private/var/mobile/Containers/Data/Application/95982B17-2C5F-4E3F-8AD7-FB90F557B991/Documents/:
let fileManager = FileManager.default
if let docDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first {
do {
let docs = try fileManager.contentsOfDirectory(at: docDirectory, includingPropertiesForKeys: [], options: .skipsHiddenFiles)
print("Files in ~/Documents are: ")
for doc in docs {
print(doc)
}
} catch let error {
Logger.printLogEntry(message: "Could not get content of documents directory: \(error.localizedDescription)", category: .dev
)
}
}
But when I then add a path like so
let filePath = docDirectory.appendingPathComponent("products.json")
print("File Path is: ", filePath)
it gives me the following path: file:///var/mobile/Containers/Data/Application/95982B17-2C5F-4E3F-8AD7-FB90F557B991/Documents/
This is different on the simulator; paths there remain the same (without the private stuff in front...
Can anyone explain that to me? To be clear, I need to copy / access in different methods, so understanding the way it's accessing differently is crucial to me.
So that hopefully for someone else to be more successful to get an answer when researching this:
/var and /private/var` point to the same folder on a real device, as one is an alias of the other, as mentioned in the comments above. So thanks to the commenters for their hints.

Resources