How to access the UserDefaults file folder on my ios application - ios

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)

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

How to correctly reference/retrieve a temp file created in AppData for file upload to a server?

So the app I'm making creates a file called "logfile" and I'm trying to send that file via Alamofire upload to a server. The file path printed in the console log is
/var/mobile/Containers/Data/Application/3BE13D78-3BF0-4880-A79A-27B488ED9EFE/Documents/logfile.txt
and the file path I can use to manually access the log created in the .xcappdata is
/AppData/Documents/logfile.txt
To access it, I'm using
let fileURL = Bundle.main.url(forResource: "", withExtension: "txt")
where inbetween the double quotes for "forResource", I've tried both file paths I listed in the previous paragraph as well as just the file name but I'm getting a nil value for file found for either. The file isn't recognized to be there, presumably because the file path I'm using is wrong as Alamofire is returning nil when trying to locate send the file. Anyone know the direct file path I'm supposed to use to be able to grab my file since the other two don't supposedly work? Thank you!
Use below code to get string data from text file to upload to server:
let fileName = "logfile"
let documentDirURL = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileURL = documentDirURL.appendingPathComponent(fileName).appendingPathExtension("txt")
print("FilePath: \(fileURL.path)")
var readString = "" // Used to store the file contents
do {
// Read the file contents
readString = try String(contentsOf: fileURL)
} catch let error as NSError {
print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription)
}
print("File Text: \(readString)") // Send 'readString' to server
If you're dynamically creating the file at runtime, it won't be in your app bundle so the Bundle class won't be able to find it. The directories you see are also dynamically-generated and not only platform-specific, but also device-specific, so you can't use the file paths directly. Instead, you'll have to ask for the proper directory at runtime from the FileManager class, like this:
guard let documents = FileManager.default.urls(for: .documentsDirectory, in: .userDomainMask).first else{
// This case will likely never happen, but forcing anything in Swift is bad
return
}
let logURL = URL(string: "logfile.txt", relativeTo: documents)
do{
let fileContents = String(contentsOf: logURL)
// Send your file to your sever here
catch{
// Handle any errors you might've encountered
}
Note that I'm guessing based on the paths you pasted in your answer you put it in your application's documents directory. That's a perfectly fine place to put this type of thing, but if I'm wrong and you put it in a different place, you'll have to modify this code to point to the right place

How to store and view the file in Iphone using IOS Swift

I am new to swift and trying to save the file on iphone and view them using file manager app present in app store. but every time the path looks like its getting stored in my mac machine. below is code which i have written for storing a simple text file
func saveImageDocumentDirectory(){
let str = "Super long string here"
let filename = getDocumentsDirectory().appendingPathComponent("output.txt")
do {
try str.write(to: filename, atomically: true, encoding: String.Encoding.utf8)
print(filename.path)
} catch {
// failed to write file – bad permissions, bad filename, missing permissions, or more likely it can't be converted to the encoding
}
}
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
but path at which file is getting stored is printed as below
/var/mobile/Containers/Data/Application/ACBC0B24-XXXX-XXXX-XXXX-BDAA4901EA41/Documents/output.txt

SQlite Cipher IOS

This here i have shared to show that i have Sqlite file present in copy bundle resources : I am using Sqlitecipher in my iOS app when run my app in Simulator (offline) it shows all of the data successfully and every query works fine like (update,delete,insert) but when testing my app on device it doesn't shows up anything. Following way i tried it :
Saved Sqlite file in bundle
Copied Sqlite file from bundle to Document Directory
Delete app from Simulator and reset my Simulator but i am still facing the same issue. Kindly suggest solution ( its a Salesforce native App )
This is the code to get file from bundle to Document Directory in Appdelegate:`
func copyFile()
{
var documents: NSString
documents = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
let bundlePath = NSBundle.mainBundle().pathForResource("LeadWork1", ofType: "sqlite")
print(bundlePath, "\n") //prints the correct path
let destPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
let fileManager = NSFileManager.defaultManager()
let fullDestPath = NSURL(fileURLWithPath: destPath).URLByAppendingPathComponent("LeadWork1.sqlite")
let fullDestPathString = fullDestPath.path
print(fullDestPathString)
print(fileManager.fileExistsAtPath(bundlePath!)) // prints true
if fileManager.fileExistsAtPath(bundlePath!) == true
{
print("File Exist")
}
else
{
do{
try fileManager.copyItemAtPath(bundlePath!, toPath: [enter image description here][1]fullDestPathString!)
}catch{
print("\n")
print(error)
}
}
let error = sqlite3_open(fullDestPathString!, &database)
if error != SQLITE_OK
{
print("Error while opening");
}
else
{
// print(fileForCopy)
print(destPath)
print("already open");
}
}`
Help will be appreciated!
Just Enable following :
Select Project -> Build Setting -> Architecture Tab - > Build Release to YES
Make sure to enable Both Debug and Release to YES.
It will solve your issue .

Resources