Text file can't be created inside a folder - ios

I'm trying to create a log.txt file inside a folder of a device, but I get this error:
NSCocoaErrorDomain Code=512 "The file “log.txt” couldn’t be saved in
the folder “Logs”.
The folder Logs already exists on the device, but I still get this error. Please find my code below:
let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let logPath = path.appendingPathComponent("Logs").appendingPathComponent("log.txt")
try! "Hello world".write(to: logPath, atomically: true, encoding: .utf8)
However, if I replace the logPath with path.appendingPathComponent("log.txt"), it will work, BUT it creates the file outside of the folder Logs instead of inside.
How can I solve this?

I have fixed this problem by using the new function called appending(component:_) of the FileManager API.
The old one that I used in my question was not deprecated, but it did not work, and I still have no idea.
However, using the new one above makes everything works just fine.

Related

How to display any extension file from server to your mobile in swift ios?

I am very new to this IOS swift programming. So need some suggestion and help. I am creating an app in which I have to show different file coming from the server. Below is the kind of link from which my file data is coming.
http://demo.xxxx.com/dctm-rest/repositories/iol_ref2/objects/0900a18480383d14/content-media?format=pdf&modifier=&page=0
This above link is for pdf or it can be of any type (txt, doc, img etc) so I have tried so many things but I was unable to get a result.
Solutions What I have tried:-
With basic auth, I am requesting URL and getting contents from the file, so I was getting data from server and printing on console but when I tried to copy that contents to one file it says unable to copy says no such file or folder exist but I have properly defined the path location. Below is my code link which I have asked earlier.
How to read data from file placed in server through url link in ios swift (4)?
Someone suggested using Alamofire lib that also I have used but no luck. Below is the code which I have referred.
Alamofire: finished with error - code: -1001
So let me know what I am doing is correct or not or is there any new method or way I can try. I have tried web view too. So please help me with this.
Thanks in advance
I use code like this to download a file and store it locally.
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentsURL.appendingPathComponent(documentFilename)
return (fileURL, [.removePreviousFile])
}
Alamofire.download(url, to: destination).response { [unowned self] response in
// check download and call completion handler
}
What code did you use to download the file?

Loading document in shared documents folder into WKWebView

I am having problems trying to load a document into a WKWebView when the document has been added to the app using iTunes file sharing.
If I include the file inside the app I can load it fine.
I am using this code to get the load the file:
let documentsURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fooURL = documentsURL.appendingPathComponent(docFileName)
let docURL = URL(fileURLWithPath: fooURL.path)
let req = URLRequest(url:docURL)
docView!.load(req)
docURL looks like this:
file:///var/mobile/Containers/Data/Application/432E716E-F70D-4985-814C-FFE7ECE53EF8/Documents/filename.pdf
I have tried to check the file exists using this code:
FileManager().fileExists(atPath: fooURL.path)
This returns true. I have also tried to copy the file from the documents folder into the app folder but this returns an error of file not found (again this is even after checking the file exists)
Should WKWebView be able to load from this location? Or have I missed something here?
Perhaps you are looking for loadFileURL(_:allowingReadAccessTo:)
Though I didn't see it explicitly stated in the docs, it wouldn't surprise me if the security policies of WKWebView are getting in your way, and the presence of this method alone seems to confirm that ;-)
Happy coding!

iOS10 + Xcode8 documentDirectory weird behavior

It seems the documentDirectory in Xcode8/Swift3/iOS10, in a framework, on iOS seems unwritable.
API's used / tried:
FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
( The last one does not seem to be preferred in Swift, which I can understand )
Now, whenever I try to write files to the URL returned in this area I do not seem to be capable of doing so ( both Simulator, and device ). Downloading the container or inspecting it does not show the files either ( I tried several methods of writing ). Also trying to create a directory to write into seems to fail.
The weird thing is that there is no error returned from within API's used or the FileManager itself.
Is there some horrible point I'm missing? Is it a bug I should report? Currently I moved to creating a directory in Library/ instead, as that seems to work and shouldn't be as volatile as Library/Cache/.
Code used to write ( realm.io was used before I decided to do this ):
let URLs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let data = Data.random(32) // Generates a 32 byte long random blob
try! data.write(to: URLs.last!) // Crashing here with a forced unwrap is fine
The path that you are writing to is invalid – you're passing in the directory path instead of the path to the file you want to create. You can craft a path like this:
let path = NSString(string: URLs.last!.path).appendingPathComponent("foo.txt")
Turns out you need to completely reset your Simulators and restart Xcode. Fun stuff.

Valid file path for archiverootobject and unarchiverootobject

I am making an iPhone app and in a previous question I was told that I needed a valid file path for archiverootobject and unarchiverootobject but I don't know how to make one. So what is a valid file path to save arrays of custom classes?
Follow up question: On the linked question I have set up my methods to use invalid saves but it still works would anyone know why?
You can save it to a subdirectory folder named with your bundleID inside the application support folder or you can also save it to the preferences folder located inside the library directory:
let preferencesDirectoryURL = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first!.appendingPathComponent("Preferences", isDirectory: true)
let fileURL = preferencesDirectoryURL.appendingPathComponent("fileName.plist")
print(fileURL.path) // "/var/folders/.../Library/Preferences/fileName.plist

Cannot find my file

I have copied the file to the project and I am new to coding in swift, but I assumed that the file would deploy to my device with all the resource files in the project. this is my code which fails to find the file or copy from the bundle
if let dirs = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .AllDomainsMask, true) as ? [String] {
let dir = dirs[0] //documents directory
let path = dir.stringByAppendingPathComponent(file)
var checkValidation = NSFileManager.defaultManager()
if checkValidation.fileExistsAtPath(path) {
println("FILE AVAILABLE")
} else {
println("FILE NOT AVAILABLE")
// Copy the file from the Bundle and write it to the Device:
let pathToBundledDB = NSBundle.mainBundle().pathForResource("pcQuestionDBA", ofType: "txt")
var error: NSError ?
if NSFileManager.defaultManager().copyItemAtPath(pathToBundledDB!, toPath: dir, error: & error) {
}
I know I must be doing something fundamentally wrong and any advice would be truly appreciated - thanks
An Update:
I had copied the file into the project folder, however, I deleted the file and tried to copy it in anew, and I received an error stating that the file already existed in the folder. I think I had confused Xcode with the multiple moves and variations I tried in an attempt to fix my bug and find the file. I renamed the file and started from scratch and it all works well now. Thanks so much for your quick replies, it led me to the solution in the end - cheers
The problem there is that you should be passing a path to the file but you passed the path to the directory.
Try like this:
NSFileManager.defaultManager().copyItemAtPath(pathToBundledDB!, toPath: path, error: &error)

Resources