swift 2 - file not found error when reading text file from app main bundle - ios

I added a simple text file (savedinfo.txt) to my project containing just 1 line of text. I need to read the text from within my app. I did that as below. However, for some reasons, it cannot find the file when reading it, even though sFilePath shows the file path. See debug msg below. I am using the latest Xcode 7.2.
Thanks
let sFilePath = String(NSBundle.mainBundle().pathForResource("savedinfo", ofType: "txt")
let sText = try NSString(contentsOfFile: sFilePath, encoding: NSUTF8StringEncoding)
sFilePath: Optional("/Users/user115387/Library/Developer/CoreSimulator/Devices/F3866C2A-869A-4CE5-9936-C8BC0CC5CE0D/data/Containers/Bundle/Application/A98B6D45-1C9A-4049-86F1-9502D45836B0/TableViewDemo.app/savedinfo.txt")
error in reading file Error Domain=NSCocoaErrorDomain Code=260 "The file “savedinfo.txt")” couldn’t be opened because there is no such file."

This code works for me:
if let sFilePath = NSBundle.mainBundle().pathForResource("savedinfo", ofType: "txt") {
do {
let sText = try NSString(contentsOfFile: sFilePath, encoding: NSUTF8StringEncoding)
print(sText)
}catch {
}
}

Related

Error Domain=NSCocoaErrorDomain Code=257 "The file “Documents” couldn’t be opened because you don’t have permission to view it."

I have a problem accessing my files.
I am trying to create a file and send it over FTP. However, when I tried to read the file I created, I got this error message. Can you check where did I made a mistake?
The FTP upload was from https://gist.github.com/Nirma/fb9991be776107d17fdcd6ed2aa02876
The TXT file was created successfully with following codes, I can view it on my iPad simulator.
// Create TXTFile
let fileName = "test.txt"
self.save(text: "some text shown here", toDirectory: self.documentDirectory(), withFileName: fileName)
self.read(fromDocumentsWithFileName: fileName)
But the error happens when I execute the FTPupload codes.
// FTP upload
let ftp = FTPUpload(baseUrl: "XXX.XXX.XXX.XXX", userName: "XXXXXXX", password: "XXXXXXX", directoryPath: "XXXXX")
let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
do {
***let data = try Data(contentsOf: url as URL, options: [ .alwaysMapped, .uncached])***
ftp.send(data: data , with: "test.txt") { (success) in
print("success")
}
print(data)
}
catch {
print(error)
}
}
I have tracked down that the line with stars creates the error which shows I don't have the permission to view the file.
Can anyone help me? Thanks!

Saving to xml document Swift

I'm using this code to save a string to an xml file in my project
let saveTo = statisticsI.toXMLString()
let filepath = Bundle.main.url(forResource: "statistics", withExtension: "xml")
let filepathAlt = Bundle.main.path(forResource: "statistics", ofType: "xml")
print(filepathAlt!)
do {
try saveTo.write(to: filepath!, atomically: false, encoding: String.Encoding.utf8)
let contents = try String(contentsOfFile: filepathAlt!)
print("FILE CONTENTS \(contents)")
}
catch let error as NSError {
print("Error writing values \(error)")
}
Printing the file contents returns the xml correctly, but when I stop running the application, the file hasn't been updated
When the above code is run, the file has already been read by a seperate function. Is the fact that the file has already been accessed (and its path still stored in a variable) the issue?
when I stop running the application, the file hasn't been updated
You can't write into the application bundle in iOS. Try using a path into the Documents folder or some other place within the app's sandbox.

Write data into csv file inside iOS app in swift 3 [duplicate]

This question already has answers here:
Read and write a String from text file
(21 answers)
File write with [NSBundle mainBundle] fails
(5 answers)
Closed 5 years ago.
I got a problem when I was trying to write data into a csv file.
The app reads data from a csv file, and during the application running, the data will change, and when it changes, it will call a function to write the data back to the csv file, but it doesn't work. thanks a lot!!
The code is listed below
var content = ""
if content != ""{
print("have content")
}
for tag in tags{
let line = "\(tag.birdIndex),\(tag.isSeen)\n"
content = content + line
}
if let path = Bundle.main.path(forResource: "birdLogVersion1", ofType: "csv"){
do {
let data = try String(contentsOfFile: path, encoding: String.Encoding.utf8)
print(data)
}catch{
}
//let url = NSURL(fileURLWithPath: path)
do {
try content.write(toFile: path, atomically: true, encoding: String.Encoding.utf8)
//(to: url as URL, atomically: true, encoding: String.Encoding.utf8)
print("tried write")
}catch{
//error
}
}else{
}
when I call this function again, print(data) shows that data has already been written into this csv file, but when I close the app, and restart it again, the csv file still be the same, didn't change at all.
Do I have to do something like save file after write data into a csv file?
Is it right to write info into the csv file in app?
Thanks again!

Reading from ApplicationSupportDirectory in iOS

Using LXLogger I am able to write log entries to file on the device and simulator (in addition to xcode console etc).
The default location which LXLogger stores the file is under the ApplicationSupportDirectory.
LXLogger writes to the file OK, and I can see the file is on my device (or on my mac HDD when using the simulator), but when I try to open the file I am told that the file does not exist.
I have added the error logs generated in line with the code.
I've tried a dozen different methods and multiple questions on here, to no avail.
let directory = NSFileManager.defaultManager().URLsForDirectory(.ApplicationSupportDirectory, inDomains: .UserDomainMask).first!.URLByAppendingPathComponent(NSBundle.mainBundle().bundleIdentifier!, isDirectory: true).URLByAppendingPathComponent("logs", isDirectory: true)
do {
let array = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(directory, includingPropertiesForKeys: nil, options:[])
var str = array[0].description
str = str.stringByReplacingOccurrencesOfString("file://", withString: "", options: .LiteralSearch, range: nil)
let fileURL = NSURL(fileURLWithPath:str)
log.info("fileURL contains: " + fileURL.absoluteString)
do {
log.info("Attempting to get contentsOfURL")
let data = try NSString(contentsOfFile: array[0].description,
encoding: NSASCIIStringEncoding)
logTextView.text = data as String
} catch let error as NSError {
log.error(error.description)
}
}
catch let error as NSError {
log.error(error.description)
}
Log Outputs from above code:
> 2016-03-31 21:43:52.121 [INFO] fileURL contains: file:///private/var/mobile/Containers/Data/Application/2F812C06-E204-4543-905C-F884C35DA198/Library/Application%2520Support/myname.myapp/logs/1_log.txt
> 2016-03-31 21:43:52.122 [INFO] Attempting to get contentsOfURL
> 2016-03-31 21:43:52.123 [ERROR] Error Domain=NSCocoaErrorDomain Code=260 "The file “1_log.txt” couldn’t be opened because there is no such file." UserInfo={NSFilePath=file:///private/var/mobile/Containers/Data/Application/2F812C06-E204-4543-905C-F884C35DA198/Library/Application%20Support/myname.myapp/logs/1_log.txt, NSUnderlyingError=0x1376e0e00 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
So the code shows that the file is there (and i can physically open the copy on my mac), but the app can't find it.
Presumably its something to do with my usage of the file handle/nsurl/something like that??
Your approach of taking the NSURL from array and using stringByReplacingOccurrencesOfString and fileURLWithPath and then description is wrong; it doesn't correctly handle the percent-encoding in the URL and it's generally complex/fragile.
This can be much simpler, because you already have a file URL returned in the array from contentsOfDirectoryAtURL. You can just use it directly:
let data = try String(contentsOfURL: array[0], encoding: NSUTF8StringEncoding)

How can I open a txt file in local directory in swift2?

I've put a "restaurants.txt" file in the same directory with MenuViewController.swift.
Then I put this code in viewDidLoad() of MenuViewController to read the file.
if let path = NSBundle.mainBundle().pathForResource("restaurants", ofType: "txt") {
if let content = try? String(contentsOfFile: path, encoding: NSUTF8StringEncoding) {
print(content)
} else {
print("error1")
}
} else {
print("error")
}
Then I get "error1" in my console.
How can I read the file in the same directory of the swift file?
Or do I have to put my "restaurants.txt" file somewhere else?
Add the file to the target:
Select the file
In the Project Navigator command1 select the file icon
Under "Target Membership" click the checkbox for the file.
1) If you wish to read content of a text file, even without inserting it to your project, you may also use NSFileMananger. The following code works, the only drawback - you need to state full path.
let fullPath = "/your/full/path/restaurants.txt"
if NSFileManager.defaultManager().fileExistsAtPath(fullPath){
do
{
let content = try String(contentsOfFile: fullPath, encoding: NSUTF8StringEncoding)
print("\(content)")
}
catch let error as NSError
{
print("error reading file: \(error)")
}
}
2) If you do mind the hardcode, and want it more generic - you will have to change Settings in the Build in Xcode. See here:
Locate source project directory in Swift

Resources