I am trying to familiarize myself with objective C, and my current goal is to read a list of items in a text file and store them in a NSString array.
Currently this is what I have:
NSString *filepath = [[NSBundle mainBundle] pathForResource:#"myList" ofType:#"txt"];
NSData* data = [NSData dataWithContentsOfFile:filepath];
NSString* string = [[NSString alloc] initWithBytes:[data bytes]
length:[data length]
encoding:NSUTF8StringEncoding];
NSString* delimiter = #"\n";
listArray = [string componentsSeparatedByString:delimiter];
I am not sure if this matters, but myList.txt is in my Supporting Files.
At the moment, I only have one item in my list. However I am unable to store even that 1 item into my listArray.
I am sure it is something silly that I am missing, I am just new to Objective C.
EDIT:
I apologize for not mentioning this earlier. I AM NOT receiving any sort of error. My array is just null.
I'm going to suggest a little simplification which might solve your problem since I can't say what your problem is. From the information I'm not sure if you are getting the proper file contents when reading it in or not.
NSString *filepath = [[NSBundle mainBundle] pathForResource:#"myList" ofType:#"txt"];
NSError *error;
NSString *fileContents = [NSString stringWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:&error];
if (error)
NSLog(#"Error reading file: %#", error.localizedDescription);
// maybe for debugging...
NSLog(#"contents: %#", fileContents);
NSArray *listArray = [fileContents componentsSeparatedByString:#"\n"];
NSLog(#"items = %d", [listArray count]);
If the content of the file is just like:
[{"Title":"20","Cost":"20","Desc":""},{"Title":"10","Cost":"10.00","Desc":""},{"Title":"5","Cost":"5.00","Desc":""}]
try this
-(id)readFromDocumentDBFolderPath:(NSString *)fileName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
NSFileManager *fileManager=[NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:appFile])
{
NSError *error= NULL;
NSData* data = [NSData dataWithContentsOfFile:appFile];
id resultData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
if (error == NULL)
{
return resultData;
}
}
return NULL;
}
Related
From couple of days I was searching of how to play ogg on iPhone. But not successful. I found this post which points towards precompiled-ogg-vorbis-libraries-for-ios, but I don't know how to use this framework or libraries. I am new in coding. I also found this post
but it plays ogg audio from bundle. I want to play from a given url, like wikipedia audios. any help will be great. Thanks
UPDATE:
I found another library or file which can be use in iOS but, still I don't know how to use in Xcode. Ogg Vorbis I audio decoder by Sean Barrett. Any idea how to use this.
UPDATE 2:
Just tried to use it something like this, but output file have no sound. Any idea where I am going wrong.
NSString *file = #"http://upload.wikimedia.org/wikipedia/commons/b/b2/En-us-Pakistan.ogg";
NSURL *fileURL = [NSURL URLWithString:file];
NSData * data = [NSData dataWithContentsOfURL:fileURL];
unsigned char* array = (unsigned char*) [data bytes];
int len = [data length];
if (data != nil) {
NSLog(#"\nis not nil");
//NSString *readdata = [[NSString alloc] initWithContentsOfURL:(NSData *)data ];
stb_vorbis* Stream = stb_vorbis_open_memory(array, len, NULL, NULL);
if (Stream)
{
stb_vorbis_close(Stream);
//return true;
}
else
{
//return false;
}
}
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [data bytes], len);
NSData *ddata = [NSData dataWithBytes:byteData length:len];
if (ddata == nil) {
NSLog(#"data nil");
}
else{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"wikiaudio"];
NSError *error;
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder if it doesn't already exist
NSString * filename = [#"hello" stringByAppendingString:#".mp3"];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", dataPath,filename];
[ddata writeToFile:filePath atomically:YES];
NSLog(#"filepath %#", filePath);
}
Its like this, in my app, I have a UIScrollView on it is a thumbnail view, they are images from my NSCachesDirectory.
I saved them from my picker then named them in my array like: images0.png,images.1.png... etc
So for example I have images in my directory this way : images0.png, images1.png, images2.png, images3.png.
Then I delete images1.png, the remaining images will be like this : images0.png,images2.png, images3.png right?
What I wanted to achieve is get the images in NSDocumentsDirectory then renamed them AGAIN or sort them again like images0.png, images1.png, images2.png...etc again?
is this possible? hope you could help me.
Use this NSFileManger moveItemAtPath: toPath: error: but you should supply the toPath:same_path_but_different_filename. This moves the file to a new path with new file name that you provide. see this
Since it seems you want the whole logic to rename your images file, here is the code you can try provided the files are in the Document directory
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString * oldPath =[[NSString alloc]init];
NSString * newPath =[[NSString alloc]init];
int count=0;
for (int i=0; i<=[[fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil]count]; i++) {
oldPath=[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"images%d.png",i]];
if ([fileManager fileExistsAtPath:oldPath]) {
newPath=[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"images%d.png",count]];
[fileManager moveItemAtPath:oldPath toPath:newPath error:nil];
count+=1;
}
}
Apple doesnot allow renameing of file saved. So alternative is to get all contents at document directory like this:
NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:yourDocDirPath error:NULL];
Now sort like this:
NSSortDescriptor * descriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending: YES comparator:^NSComparisonResult(id obj1, id obj2){
return [obj1 compare: obj2 options: NSNumericSearch];
}];
NSArray * sortedDirectoryContent = [directoryContent sortedArrayUsingDescriptors:[NSArray arrayWithObject: descriptor]];
We have sorted array rewrite all files with new name:
for(NSString *fileName in sortedDirectoryContent)
{
NSString *filePath = [yourDocDirPath stringByAppendingPathComponent:fileName];
NSData *fileData = [[NSData alloc]initWithContentsOfFile:filePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
if(fileData)
{
NSString *newFilePath = [yourDocDirPath stringByAppendingPathComponent:#"New Name here"];
[fileData writeToFile:newFilePath atomically:YES];
}
}
else
{
if(fileData)
{
NSString *newFilePath = [yourDocDirPath stringByAppendingPathComponent:#"New Name here"];
[fileData writeToFile:newFilePath atomically:YES];
}
}
}
I save in NSDocumentDirectory this way:
NSLog(#"%#", [info objectAtIndex:i]);
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask ,YES );
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"Images%d.png", i]];
ALAssetRepresentation *rep = [[info objectAtIndex: i] defaultRepresentation];
UIImage *image = [UIImage imageWithCGImage:[rep fullResolutionImage]];
//----resize the images
image = [self imageByScalingAndCroppingForSize:image toSize:CGSizeMake(256,256*image.size.height/image.size.width)];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:YES];
I know how to delete all the images in NSDocumentDirectory.
But I was wondering on how to delete all of the images with the name of oneSlotImages.
Thanks
Try this ,just copy this code,your images with name oneSlotImages,will be removed from DocumentDirectory ,its just simple :
NSArray *directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] error:NULL];
if([directoryContents count] > 0)
{
for (NSString *path in directoryContents)
{
NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:path];
NSRange r =[fullPath rangeOfString:#"oneSlotImages"];
if (r.location != NSNotFound || r.length == [#"oneSlotImages" length])
{
[[NSFileManager defaultManager] removeItemAtPath:fullPath error:nil];
}
}
}
Have you looked at NSFileManager's methods? Maybe something like this called in a loop for all of your images.
[[NSFileManager defaultManager] removeItemAtPath:imagePath error:NULL];
Use like,
NSArray *dirFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:strDirectoryPath error:nil];
NSArray *zipFiles = [dirFiles filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"self CONTAINS[cd] %#", #"oneSlotImages"]];
The array zipFiles contains the names of all the files we filtered. Thus by appending the filenames with complete path of document directory with in a loop, you can make the full filepath of all the filtered files in the array. Then you can use a loop and call the method of NSFileManager object like below
[fileManager removeItemAtPath: strGeneratedFilePath error: &err];
which removes the itm at path from the directory.
By this way you can filter out the filenames contains oneSlotImages. So you can prefer to delete this ones. Hope this helps you.
As this is an old question now and also above answers shows how to delete by image name.What if I want to delete everything from NSDocumentDirectory at one shot, use the below code.
// Path to the Documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if ([paths count] > 0)
{
NSError *error = nil;
NSFileManager *fileManager = [NSFileManager defaultManager];
// Print out the path to verify we are in the right place
NSString *directory = [paths objectAtIndex:0];
NSLog(#"Directory: %#", directory);
// For each file in the directory, create full path and delete the file
for (NSString *file in [fileManager contentsOfDirectoryAtPath:directory error:&error])
{
NSString *filePath = [directory stringByAppendingPathComponent:file];
NSLog(#"File : %#", filePath);
BOOL fileDeleted = [fileManager removeItemAtPath:filePath error:&error];
if (fileDeleted != YES || error != nil)
{
// Deal with the error...
}
}
}
i am new developer in iphone application. i would like write a content in xml file for that, i have created xml file and write tags with element, attribute and value with some data in that xml as follows.
-(void)writexmlfile:(NSString *)data toFile:(NSString *)fileName NodeName:(NSString *)Node{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
NSString *fileExtension = [NSString stringWithFormat:#"%#%#",fileName,#".xml"];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileExtension];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:appFile];
if(fileExists) {
NSError *error = nil;
NSString *docStr;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:appFile];
if(fileExists)
{
NSLog(#"file exist in document");
NSData *myData1 = [NSData dataWithContentsOfFile:appFile];
if (myData1) {
docStr = [[NSString alloc] initWithData:myData1 encoding:NSASCIIStringEncoding];
XMLString = [[NSMutableString alloc]initWithString:docStr];
[self XMLString];
NSLog(#"data%#",XMLString);
}
}
// [XMLString insertString:data atIndex:index];
[XMLString appendFormat:#"<%#>%#</%#> \n",Node,data,Node];
BOOL success = [XMLString writeToFile:appFile atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!success) {
NSLog(#"Error: %#", [error userInfo]);
}
else {
NSLog(#"File write is successful");
}
}
}
i want add new tag with new elements,new attributes,etc.,if i enter element at the place of tag it is modifying with previous tag .
here how can i append the new tag to previous appended tags
please any body could help me
Thanks in advance
As a suggestion, you can use APXML to create XML documents it is very simple and easy to use. This post can guide you further.
im getting a "CFDictionaryAddValue(): immutable collection 0xd5aea0 given to mutating function"
error when i try to write a string to a file using the follwowing code
NSString *xmlString = [NSString stringWithString:xmlData];
NSError *error = nil;
if ([xmlString writeToFile:filePath atomically:NO encoding:NSASCIIStringEncoding error:&error])
xmlData was a mutable string but xmlString is not.
any ideas?
It works for me in cocoa.
NSString * xmlData = #"This is some random string";
NSString * xmlString = [NSString stringWithString:xmlData];
NSError * error = nil;
if (![xmlString writeToFile:#"data.txt"
atomically:NO
encoding:NSASCIIStringEncoding
error:&error])
{
NSLog(#"writeToFile failed: %#", error);
}
I would check:
How do you get xmlData? Is it a NSString?
Do you specify file path within your app bundle? You will not be able to write outside your application directory apart from Documents (?) I think.
This is how you would specify file in Documents directory:
// Documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
// <Application Home>/Documents/foo.plist
NSString *fooPath = [documentsPath stringByAppendingPathComponent:#“foo.plist”];