Can't read text file from desktop using objective-c - objective-c

Can anyone help me to find what's wrong with my code while reading file from desktop
NSString *filename=#"~/Users/user12345/Desktop/Sample/Data.txt";
NSString *fileString=[NSString stringWithContentsOfFile:filename encoding:NSUTF8StringEncoding error:nil];
NSArray *namesArray=[fileString componentsSeparatedByString:#"\n"];
for(NSString *names in namesArray)
{
NSLog(#"names:%#",names);
}

If you want to use the tilde – which represents /User/<currentUser>/ – you have to ...expandingTildeInPath and remove /Users/user12345
NSString *filename = [#"~/Desktop/Sample/Data.txt" stringByExpandingTildeInPath];
that makes the path independent of the current user name, otherwise remove the tilde:
NSString *filename = #"/Users/user12345/Desktop/Sample/Data.txt";
Caveat: If your app is sandboxed the path does not point to the visible desktop.

NSString *filename=#"~/Users/user12345/Desktop/Sample/Data.txt";
The ~ used in a path is a convention which means your home directory, but it doesn't work in all contexts (e.g. when used in -stringWithContentsOfFile:`) and you've supplied an absolute path anyway. Remove it from the front of your path
NSString *filename=#"/Users/user12345/Desktop/Sample/Data.txt";
and it should work as long as the file does actually exist at that path.

Related

Issues playing local files with AVPlayer?

Basically, I'm writing a video file to the Application Support directory and then saving it's path:
NSString *guid = [[NSUUID new] UUIDString];
NSString *outputFile = [NSString stringWithFormat:#"video_%#.mp4", guid];
NSString *outputDirectory = [NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *tempPath = [outputDirectory stringByAppendingPathComponent:outputFile];
NSURL *fileURL = [NSURL fileURLWithPath:tempPath]
// code to write a video to fileURL
I save the string path itself by calling [fileURL path];
Now later when I try to create an AVAssetItem from it, I can't actually get it to play.
EDIT:
Ok, so it seems the issue is the space in Application Support. I tried saving the file to just the Library directory and it worked fine.
So the question becomes, how can I play a video I save in the Application Support directory. I wasn't able to create a valid NSURL without escaping the space (when I tried it would return a nil NSURL) but it seems that the space/escaping doesn't allow it to play correctly.
Assume the NSURL to NSString conversion is required (unless it really should be avoided).
Also, side note, but if anyone could give some insight as to why this question was down voted so I can improve the quality of my questions, that would be appreciated. I don't understand?
While I am not informed enough to opine about whether this would change if I had used matt's recommended methods: URLForDirectory:inDomain:appropriateForURL:create:error: and URLByAppendingPathComponent: the actual issue here isn't converting an NSURL to NSString
It's that I'm saving the full URL ([fileURL path]). This is because the [NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES) objectAtIndex:0]; dynamically changes and the full path won't always point me to the appropriate file.
Instead I need to save just the name of my file (in my case I needed to persist outputFile) and then later dynamically build the the full path when I need it.
The same exact process:
NSString *outputDirectory = [NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *tempPath = [outputDirectory stringByAppendingPathComponent:outputFile];
NSURL *fileURL = [NSURL fileURLWithPath:tempPath];
worked just fine.
TLDR: Saving a full path doesn't work

Get directory path from full filepath

New to objective-c. How do I get the directory from a full file path?
so if I have
/User/Test/Desktop/test.txt
I want
/User/Test
Also is there an equivalent to Path.Combine from .NET in Objective-C?
-[NSString pathComponents] returns an NSArray of path components.
For instance
NSString *path = #"/User/Test/Desktop/test.txt";
NSArray *components = [path pathComponents];
NSLog(#"%#", components); //=> ( /, User, Test, Desktop, test.txt )
Then you can take only the components you need and build a new path with them, for instance
NSString *newPath =
[NSString pathWithComponents:
[components subarrayWithRange:(NSRange){ 0, components.count - 2}]];
NSLog(#"%#", newPath); // => /User/Test/
Read the Working with Paths section of Apple's NSString documentation, you will find methods that answer your questions. For example, stringByDeletingLastPathComponent removes the last component of a path leaving the containing directory.

Reading text file with NSString:stringWithContentsOfFile?

Reading text file with NSString:stringWithContentsOfFile?
NSString *txtFilePath = [[NSBundle mainBundle] pathForResource:#"\help" ofType:#"txt"];
NSString *txtFileContents = [NSString stringWithContentsOfFile:txtFilePath encoding:NSUTF8StringEncoding error:NULL];
NSLog(#"File: %#",txtFileContents);
I get "null" as the result. How do I know what path to specify?
thanks
(I placed the file just under "Groups and Files" ... so not sure if I need to specify a path or just the file name. Maybe there is something else wrong ???
I think the backslash in your path is confusing things. Try this:
NSString *txtFilePath = [[NSBundle mainBundle] pathForResource:#"/help" ofType:#"txt"];
Also, as noted in the comments, you need to use the Build Phase of your project to copy the "help.txt" file.
Try this. What you want is the path to help.txt but you have to split it up into its name and extension for the method to work.
NSString *txtFilePath = [[NSBundle mainBundle] pathForResource: #"help" ofType: #"txt"];
It also wouldn't hurt to specify NULL instead of nil for the error argument. This is because nil represents objects whereas NULL represents pointers.
Here's a common file that I include in a ton of my projects (.h first, followed by .m):
I name this one FileHelpers.h:
#import <UIKit/UIKit.h>
NSString *pathInDocumentDirectory(NSString *fileName);
I name this one (of course) FileHelpers.m:
#include "FileHelpers.h"
NSString *pathInDocumentDirectory(NSString *fileName)
{
// Get list of document directories in sandbox
NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// Get one and only one document directory from that list
NSString *documentDirectory = [documentDirectories objectAtIndex:0];
// Append passed in file name to that directory, return it
return [documentDirectory stringByAppendingPathComponent:fileName];
} // pathInDocumentDirectory
As an aside, I have to admit that I didn't come up with this solution myself, but it's been so long that I've used it that I can't remember now where I got it. If anyone knows, please feel free to attribute the appropriate credit!

File write with [NSBundle mainBundle] fails

I am trying to take content from one file and write it into another. I am reading fine, but I am not able to write it into another file.
I have a database of words. I want to separate the words into different files based on the number of letters. All four letter words go into one file, and so on. I added a txt file called "4letter" into my resources and the following is my code:
NSError *error;
//READ
NSString *dbFile = [[NSBundle mainBundle] pathForResource:#"words" ofType:#"txt"];
NSString *test = [NSString stringWithContentsOfFile:dbFile encoding:NSUTF8StringEncoding error:&error];
//convert from string to array
NSArray *lines = [test componentsSeparatedByString:#"\n"];
NSFileHandle *logFile = nil;
logFile = [NSFileHandle fileHandleForWritingAtPath:[[NSBundle mainBundle] pathForResource:#"4letter" ofType:#"txt"]];
//Test if write works
for (int i=0; i<5; i++)
{
NSString *randomAnagram = [[lines objectAtIndex:i] lowercaseString];
[logFile writeData: [randomAnagram dataUsingEncoding: NSNEXTSTEPStringEncoding]];
}
In iOS, you can't write into a file in your app's bundle -- the entire bundle is read-only. Use a path into the Documents folder instead.
See special File System Programming Guide for better understnading.
In iOS, you can't write into a file in your app's bundle -- the entire bundle is read-only.
Consider reading iOS Data Storage Guidelines to better understand the purpose of directories below, in context of iCloud backup.
<Application_Home>/AppName.app
This is the bundle directory containing the app itself. Do not write
anything to this directory. To prevent tampering, the bundle directory
is signed at installation time. Writing to this directory changes the
signature and prevents your app from launching again.
<Application_Home>/Documents/
Use this directory to store critical user documents and app data
files. Critical data is any data that cannot be recreated by your app,
such as user-generated content. The contents of this directory can be
made available to the user through file sharing. The contents of this
directory are backed up by iTunes.
<Application_Home>/Library/
This directory is the top-level directory for files that are not user
data files. You typically put files in one of several standard
subdirectories but you can also create custom subdirectories for files
you want backed up but not exposed to the user. You should not use
this directory for user data files. The contents of this directory
(with the exception of the Caches subdirectory) are backed up by
iTunes. For additional information about the Library directory, see
“The Library Directory Stores App-Specific Files.”
See full list (tmp/, Documents/Inbox) in iOS Standard Directories: Where Files Reside
UPDATE
I use NSFileManager method URLForDirectory:inDomain:appropriateForURL:create:error:
Like Caleb said, you can't write to your app's directory, but you can write to your app's Documents folder. You can get it like this:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
Your app's bundle is read-only. There is two ways I could see:
1) Write in documents folder:
NSArray *pathList = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path =  [myPathList  objectAtIndex:0];
2) Use sqlite database. This is the same as 1 (you must save db in documents anyway), but you're using sqlite database. I think this is better than a lot of txt and plist files: here's a tutorial on the topic.
I use the following code :
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:#"set.txt"];
NSString *data=#"Kostas";
[data writeToFile:appFile atomically:YES];
NSString *myData = [NSString stringWithContentsOfFile:appFile];
NSLog(#"Data : %# ",myData);

Failure to write NSString to file on iPad

I'm using a text file to save the changes made by a user on a list (the reason that I'm doing this is so that I can upload the text file to a PC later on, and from there insert it into an Excel spreadsheet). I have 3 data structures: A NSMutableArray of keys, and a NSMutableDictionary who's key values are MSMutableArrays of NSStrings.
I iterate through these data structures and compile a file string that looks much like this:
(Key);(value)\t(value)\t(value):\n(Key);(value).. .so on.
SO, onto the actual question: When I attempt to save it, it fails. I'm 99% sure this is because of the file path that I'm using, but I wanted backup to check this out. Code follows:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *filePath = [paths objectAtIndex:0];
NSString *fileString = [NSString stringWithString:[self toFileString]];
if(![fileString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:NULL]){
NSLog(#"File save failed");
} else {
// do stuff
}
(Code above is re-copied, since the actual code is on a different computer. It compiles, so ignore spelling errors?)
I tried using NSError, but I got bogged down in documentation and figured I might as well ask SO while trying to figure out how to properly use NSError (might be a little bit of an idiot, sorry).
99% sure it's the NSArray *paths line that's tripping it up, but I don't know how else to get the documents directory.
Edit: Problem solved, and one final question: If I save it to the App's document directory, where can I go after I close the app to see if it saved properly? If it works like I think it does, isn't it sandboxed in with the app's installation on the simulator? (i.e. no way of checking it)
NSLog() that filePath string. I think you're trying to write to the directory itself, not to a file.
Try this instead:
filePath = [[paths objectAtIndex:0]stringByAppendingPathComponent:#"myfile.txt"];
What is the file name you want to save? The method
NSArray *paths = NSSearchPathForDirectoriesInDomains(...);
NSString *filePath = [paths objectAtIndex:0];
...
if(![fileString writeToFile:filePath ...
means you are saving the string into a file path which has the same name as a folder. This will of course fail. Please give it a name, e.g.
NSString* fileName = [filePath stringByAppendingPathComponent:#"file.txt"];
if(![fileString writeToFile:fileName ...
and try again.
BTW, to use NSError:
NSError* theError = nil;
if(![fileString writeToFile:fileName ... error:&theError]) {
// ^^^^^^^^^
NSLog(#"Failed with reason %#", theError);
// theError is autoreleased.
}