Advertise Mobile SDKs Books Events Forum News Social Networking Support Us
Follow @iphonedevsdk on Twitter

Interface 2, Advanced iOS
Mockup & Code Gen
($9.99)

Make your own iPhone apps
and run them live!
(free)

Pic Frame Dynamo: Photo Editing
($0.99)

Abiliator
($1.99)

Want your application or service advertised on iPhone Dev SDK?

Go Back   iPhone Dev SDK Forum > iPhone SDK Development Forums > iPhone SDK Development

Reply
 
LinkBack Thread Tools Display Modes
Old 07-10-2008, 11:36 AM   #1 (permalink)
Registered Member
 
Join Date: Jul 2008
Posts: 38
Xavier is an unknown quantity at this point
Default Read / write / create data files

Hi,

I just started to develop applications for iPhone, and I'm actually trying to access files in order to read or write data.
I can successfully read a raw data file, but I'm having some problems about writing.
Here is the small piece of code I wrote:

Code:
	char *saves = "abcd";
	NSData *data = [[NSData alloc] initWithBytes:saves length:4]; 
	BOOL test = [self writeToFile:data:@"data":@"iph"];

- (BOOL)writeToFile:(NSData *)data:(NSString *)fileName:(NSString *)extension 
{
	NSFileManager *fm = [NSFileManager defaultManager];
	NSString *appFile = [[NSBundle mainBundle] pathForResource:fileName ofType:extension];
	
	if (!appFile)  // if file doesn't exist, create it
	{
		printf("File %s doesn't exist, so we create it", appFile);
		return ([fm createFileAtPath:appFile contents:data attributes:nil]);
	}
	else
		return ([data writeToFile:appFile atomically:YES]); 	
}
The writeToFile method returns a YES, but nothing is written into my file.
(By the way the file creation isn't working too).

Did you already managed to write into a file this way ?

Thanks !
Xavier is offline   Reply With Quote
Old 07-10-2008, 11:38 PM   #2 (permalink)
Registered Member
 
Join Date: May 2008
Posts: 57
jrgalan is an unknown quantity at this point
Default Re: Read / write / create data files

i believe the following code:
Code:
NSString *appFile = [[NSBundle mainBundle] pathForResource:fileName ofType:extension];
only searches the app dir for a resource that ALREADY exists.

this is how i write files:
Code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
	
// the path to write file
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"myFile"];

[data writeToFile:appFile atomically:YES];
jrgalan is offline   Reply With Quote
Old 07-11-2008, 03:46 AM   #3 (permalink)
Registered Member
 
Join Date: Jul 2008
Posts: 38
Xavier is an unknown quantity at this point
Default Re: Read / write / create data files

It seems that I have no permission to write in the App bundle.
I tried in the Documents directory and it's working fine.

Thanks.
Xavier is offline   Reply With Quote
Old 08-24-2008, 03:35 AM   #4 (permalink)
Registered Member
 
Join Date: Aug 2008
Posts: 268
ghost is on a distinguished road
Default

Quote:
Originally Posted by jrgalan View Post
i believe the following code:
Code:
NSString *appFile = [[NSBundle mainBundle] pathForResource:fileName ofType:extension];
only searches the app dir for a resource that ALREADY exists.

this is how i write files:
Code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
	
// the path to write file
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"myFile"];

[data writeToFile:appFile atomically:YES];
I'm trying to save GPS data so I'm using your code like this:
Code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
		NSString *documentsDirectory = [paths objectAtIndex:0];
		
		// the path to write file
		NSString *appFile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@,%@",latitude,longitude]];
		
		[data writeToFile:appFile atomically:YES];

How would I retrieve that file and save the lat and lon into 2 separate variables?

Thanks!
ghost is offline   Reply With Quote
Old 02-09-2009, 05:24 PM   #5 (permalink)
New Member
 
Join Date: Feb 2009
Posts: 2
jgoemat is on a distinguished road
Default Use NSMutableDictionary or NSMutableArray

Quote:
How would I retrieve that file and save the lat and lon into 2 separate variables?

Thanks!
You could use the NSMutableDictionary's writeToFile methods instead, I find that handy for simple data. It can basically read/write any type you can use in your plist files (Dictionary, Array, Boolean, Data, Date, Number, String).

I use a static method to return the full path to the data file so I don't have to write it twice:
Code:
+ (NSString *)dataFilePath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(
        NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDirectory = [paths objectAtIndex:0];
    return [docDirectory stringByAppendingPathComponent:@"GPS.dat"];
}
Save values:
Code:
NSMutableDictionary *dict = [[NSMutableDictionary alloc]  init];
[dict setValue:[NSNumber numberWithFloat:43.3] forKey:@"latitude"];
[dict setValue:[NSNumber numberWithFloat:-85.7] forKey:@"longitude"];
[dict writeToFile:[classname dataFilePath]];
Load and log values:
Code:
NSMutableDictionary *dict = [[NSMutableDictionary alloc] 
        initWithContentsOfFile:[classname dataFilePath]];
NSLog("%f, %f", 
        [dict valueForKey:@"latitude"], 
        [dict valueForKey:@"longitude"]);
jgoemat is offline   Reply With Quote
Old 03-16-2009, 01:01 AM   #6 (permalink)
New Member
 
Join Date: Mar 2009
Posts: 9
aanupaul is on a distinguished road
Default can read music files

can read music files stored in iphone to my apps.

if anybody know pls reply as soon as possible.....
Thanks...
aanupaul is offline   Reply With Quote
Old 03-30-2009, 03:21 AM   #7 (permalink)
Registered Member
 
Join Date: Mar 2009
Posts: 42
fulvio is on a distinguished road
Default

Quote:
Originally Posted by jgoemat View Post
You could use the NSMutableDictionary's writeToFile methods instead, I find that handy for simple data. It can basically read/write any type you can use in your plist files (Dictionary, Array, Boolean, Data, Date, Number, String).

I use a static method to return the full path to the data file so I don't have to write it twice:
Code:
+ (NSString *)dataFilePath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(
        NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDirectory = [paths objectAtIndex:0];
    return [docDirectory stringByAppendingPathComponent:@"GPS.dat"];
}
Save values:
Code:
NSMutableDictionary *dict = [[NSMutableDictionary alloc]  init];
[dict setValue:[NSNumber numberWithFloat:43.3] forKey:@"latitude"];
[dict setValue:[NSNumber numberWithFloat:-85.7] forKey:@"longitude"];
[dict writeToFile:[classname dataFilePath]];
Load and log values:
Code:
NSMutableDictionary *dict = [[NSMutableDictionary alloc] 
        initWithContentsOfFile:[classname dataFilePath]];
NSLog("%f, %f", 
        [dict valueForKey:@"latitude"], 
        [dict valueForKey:@"longitude"]);
I implemented your code because I wanted to save the value of a UISwitch.

Here is my code:

I'm not sure whether this is the correct way of saving UISwitch values to a file. Unfortunately this doesn't work.

Code:
- (IBAction)switchChanged:(id)sender {
	soundEffectsMode = (UISwitch*) sender;
	
	NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
	
	BOOL currentValue = (BOOL)soundEffectsMode.isOn;
	
	if (currentValue) {
		[dict setValue:[NSNumber numberWithInt:1] forKey:@"soundEffects"];
	} else {
		[dict setValue:[NSNumber numberWithInt:0] forKey:@"soundEffects"];
	}
	[dict writeToFile:[gameOptions dataFilePath]];
	warning: 'gameOptions' may not respond to '+dataFilePath'
	warning: 'NSMutableDictionary' may not respond to '-writeToFile:'
	NSLog("%d", [dict valueForKey:@"soundEffects"]);
	warning: passing argument 1 of 'NSLog' from incompatible pointer type
}
I then want to be able to check for the value and play sound effects (in a different view) if the switch value is set to ON.

Could I do something like this?

Code:
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:[gameOptions dataFilePath]];

if ([dict valueForKey:@"soundEffects"] == 1) {
	//play sound effect
}
Also I wanted to change the default UISwitch value to OFF when the view loads. This doesn't seem to work!

Code:
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (id)initWithOptionsSetup {	
	self.soundEffectsMode.on = NO;
	return self;
}

Last edited by fulvio; 03-30-2009 at 05:40 AM.
fulvio is offline   Reply With Quote
Old 09-03-2009, 07:33 AM   #8 (permalink)
Registered Member
 
Join Date: Aug 2009
Posts: 18
mohsadster_iphone is on a distinguished road
Default Reading the filesstored in Iphone

HI,

Is der anyway to read teh files storein iphone. I heard 3.0 supports reading and saving the music files. Is it not possible to load other files as music files. I like to build a Backup and Recovery system.

Awaiting for your reply,

Thanks,
Mohammed Sadiq.
mohsadster_iphone is offline   Reply With Quote
Old 03-31-2010, 04:24 PM   #9 (permalink)
Registered Member
 
Join Date: Mar 2010
Posts: 1
pannag is on a distinguished road
Default How do i save to the Mac ?

That is great! Thanks a lot.
Is there a way in which I can access the saved files from the Mac for analysis? For example, I want to write the accelerometer data to the file and later read it in Matlab or something?
Thanks
PS

Quote:
Originally Posted by jgoemat View Post
You could use the NSMutableDictionary's writeToFile methods instead, I find that handy for simple data. It can basically read/write any type you can use in your plist files (Dictionary, Array, Boolean, Data, Date, Number, String).

I use a static method to return the full path to the data file so I don't have to write it twice:
Code:
+ (NSString *)dataFilePath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(
        NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDirectory = [paths objectAtIndex:0];
    return [docDirectory stringByAppendingPathComponent:@"GPS.dat"];
}
Save values:
Code:
NSMutableDictionary *dict = [[NSMutableDictionary alloc]  init];
[dict setValue:[NSNumber numberWithFloat:43.3] forKey:@"latitude"];
[dict setValue:[NSNumber numberWithFloat:-85.7] forKey:@"longitude"];
[dict writeToFile:[classname dataFilePath]];
Load and log values:
Code:
NSMutableDictionary *dict = [[NSMutableDictionary alloc] 
        initWithContentsOfFile:[classname dataFilePath]];
NSLog("%f, %f", 
        [dict valueForKey:@"latitude"], 
        [dict valueForKey:@"longitude"]);
pannag is offline   Reply With Quote
Old 01-03-2011, 08:06 AM   #10 (permalink)
Registered Member
 
Join Date: Jan 2011
Posts: 1
DonThunder is on a distinguished road
Default

Hey jgoemat.

I tried to understand and use your code.
I have one question left: I get an error with the "classname"
XCode tells me that it's not defined. Did you do that in your headerfile or somewhere I don't see it?

Thanks,
Don
DonThunder is offline   Reply With Quote
Old 01-04-2011, 12:17 PM   #11 (permalink)
Registered Member
 
Join Date: Jan 2011
Posts: 24
Sophie11 is on a distinguished road
Default

I am also trying to read from a file and it's causing me trouble.

I have the line of code 'NSArray *line = [fileContents componentsSeparatedByString:@"\n"];

which breaks up the data from my text file into separate strings and it's receiving the error 'Local declaration of 'txtFile' hides instance variable' for some reason?

Can anyone tell me why?
Sophie11 is offline   Reply With Quote
Old 01-17-2011, 03:59 AM   #12 (permalink)
Registered Member
 
Join Date: Jan 2011
Posts: 2
dmgdpnk is on a distinguished road
Default

Quote:
Originally Posted by Sophie11 View Post
I am also trying to read from a file and it's causing me trouble.

I have the line of code 'NSArray *line = [fileContents componentsSeparatedByString:@"\n"];

which breaks up the data from my text file into separate strings and it's receiving the error 'Local declaration of 'txtFile' hides instance variable' for some reason?

Can anyone tell me why?
Try:

NSArray *line = [[NSArray alloc] initWithArray: [fileContents componentsSeparatedByString:@"\n"]];

And make sure you do:

[line release];

somewhere.

Might be wrong - pretty new to this. Hope that helps.
dmgdpnk is offline   Reply With Quote
Old 01-17-2011, 04:02 AM   #13 (permalink)
Reading the Documentation
 
baja_yu's Avatar
 
Join Date: Sep 2010
Location: 45.255019,19.844908
Posts: 5,414
baja_yu has a spectacular aura about
Default

There really is no need to answer and bump threads from 2 years ago.
baja_yu is offline   Reply With Quote
Reply

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
Help With UIAnimation Nitrex88 please read!! fusion777 iPhone SDK Development 9 08-16-2009 08:09 PM
use Interface Builder to create a UITableViewCell martinn iPhone SDK Development 3 05-29-2009 03:30 AM
How do I create my default.png? Fastrak iPhone SDK Development 4 08-22-2008 03:18 AM
Write & Read SQL Blob fourtyfour iPhone SDK Development 0 07-09-2008 09:35 AM
Create Password TextFiled satyanarayanagv iPhone SDK Development 2 06-06-2008 12:49 PM


» Advertisements
» Online Users: 319
7 members and 312 guests
blueorb, guusleijsten, jbro, Kryckter, mer10, n00b, SLIC
Most users ever online was 1,387, 04-10-2012 at 04:21 AM.
» Stats
Members: 175,649
Threads: 94,113
Posts: 402,880
Top Poster: BrianSlick (7,990)
Welcome to our newest member, Anwerbl
Powered by vBadvanced CMPS v3.1.0

All times are GMT -5. The time now is 08:58 PM.
Powered by vBulletin® Version 3.8.0
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.3.0