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

Mockup & CodeGen, iPhone & iPad
($9.99)

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

Manu
($0.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 02-07-2010, 04:15 PM   #1 (permalink)
Registered Member
 
Join Date: Feb 2010
Posts: 4
Question Why does my file write/read not work?

I've written the following code and single stepped through it with the debugger. By the time I get to the end, readData and readString are zero length, when I expect them to be "heading\r\ndata line 1\r\ndata line 2\r\n".

Can someone please suggest why the code doesn't work? Note that I plan on holding the file open and writing more later.

Also, do I need the synchronizeFile prior to the closeFile?

And finally, any recommendation on how to [or a utility app that can] look into this applications Documents folder to see the file I'm writing? I'll also want to transfer the file to a desktop (Windows PC).

Thanks,
Helmut

CODE:

// Hgf Create record file in <Application_Home>/Documents/ folder
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDire ctory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (documentsDirectory) {
NSString* myRecordPath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: @"%@.csv", @"Recorded Date"] ];
[myRecordPath retain];
//// Create recordfile
//NSFileManager *fileManger = [NSFileManager defaultManager];
//NSString* heading = @"heading";
//NSData* fileData = [heading dataUsingEncoding: NSASCIIStringEncoding];
//if ( ![fileManger createFileAtPath:myRecordPath contents:fileData attributes: nil] ) {
// NSLog (@"Error creating recording file!\n");
//}

NSString *recordFilePath = [documentsDirectory stringByAppendingPathComponent:myRecordPath];
NSFileHandle* recordFileHandle = [NSFileHandle fileHandleForWritingAtPath:recordFilePath];
NSString* heading = @"heading\r\n";
NSData* fileData = [heading dataUsingEncoding: NSASCIIStringEncoding];
[recordFileHandle writeData:fileData];
heading = @"data line 1\r\n";
fileData = [heading dataUsingEncoding: NSASCIIStringEncoding];
[recordFileHandle writeData:fileData];
heading = @"data line 2\r\n";
fileData = [heading dataUsingEncoding: NSASCIIStringEncoding];
[recordFileHandle writeData:fileData];
[recordFileHandle synchronizeFile];
[recordFileHandle closeFile];
//NSData* readData = [recordFileHandle readDataToEndOfFile];
NSData *readData = [[[NSData alloc] initWithContentsOfFile:recordFilePath] autorelease];
NSString* readString = [[NSString alloc] initWithData:readData encoding:NSASCIIStringEncoding];
[self broadcastChatMessage:readString fromUser:/*HgF*/@"recorder"];

} else {
NSLog (@"Documents folder not found!\n");
}
Helmut Forren is offline   Reply With Quote
Old 02-07-2010, 08:36 PM   #2 (permalink)
Registered Member
 
Join Date: May 2009
Posts: 63
Default

1. You should not "retain" objects you did not "alloc".
Remove "[myRecordPath retain];"

2. check if recordFileHandle != nil

3. restart your phone, may be file was not released properly before.

4. File should exist before you can open it with "[NSFileHandle fileHandleForWritingAtPath:recordFilePath];"
softak is offline   Reply With Quote
Old 02-08-2010, 05:59 AM   #3 (permalink)
Registered Member
 
manicaesar's Avatar
 
Join Date: Feb 2009
Location: Poznań, Poland
Age: 25
Posts: 103
Default

Quote:
And finally, any recommendation on how to [or a utility app that can] look into this applications Documents folder to see the file I'm writing? I'll also want to transfer the file to a desktop (Windows PC).
You can view your application Documents folder by creating temporary web server within your app and connecting to it via browser (so it does not matter whether you have PC or Mac). To achieve this:
- Download free lightweight server written in C - Mongoose:
- Add its source files to your app files
- Use Objective-C wrapper for this server which you can find here
- Use localIPAddress method to get address for your server
- Enter the address in web browser on your computer

By default, if you do not set any uri callback function (in the wrapper it is not set), connecting to the server from web browser (iPhone and the computer you connect from should be in the same WiFi net) will result in printing contents of Documents folder of your app. You can browse it and download the files you are interested in

I hope this will be useful.
__________________
Do you like Age Of War? Have you played 'The Wars' and are not fully satisfied? Try Empires At War - we bet you will love it!


------------------
Full Version
------------------
Lite Version
------------------
YouTube Game Trailer
manicaesar is offline   Reply With Quote
Old 02-08-2010, 02:49 PM   #4 (permalink)
Registered Member
 
Join Date: Feb 2010
Posts: 4
Default

Quote:
Originally Posted by softak View Post
1. You should not "retain" objects you did not "alloc".
Remove "[myRecordPath retain];"

2. check if recordFileHandle != nil

3. restart your phone, may be file was not released properly before.

4. File should exist before you can open it with "[NSFileHandle fileHandleForWritingAtPath:recordFilePath];"
Thanks. This got me going to the next step.

1. FYI, I didn't think the retain was necessary, but got it from borrowed code.

2. recordFileHandle was indeed nil, but because I never created file. I put back in the commented-out code to create file. Then recordFileHandle still nil due to a snafu creating pathnamepathname [sic]. After fixing pathname, recordFileHandle came back non-nil

3. I did restart the phone, but the above was the cause.

4. File not previously existing plus filename snafu were my problems.

Thanks.
Helmut Forren is offline   Reply With Quote
Old 02-08-2010, 02:54 PM   #5 (permalink)
Registered Member
 
Join Date: Feb 2010
Posts: 4
Default

Quote:
Originally Posted by manicaesar View Post
You can view your application Documents folder by creating temporary web server within your app and connecting to it via browser (so it does not matter whether you have PC or Mac). To achieve this:
- Download free lightweight server written in C - Mongoose:
- Add its source files to your app files
- Use Objective-C wrapper for this server which you can find here
- Use localIPAddress method to get address for your server
- Enter the address in web browser on your computer

By default, if you do not set any uri callback function (in the wrapper it is not set), connecting to the server from web browser (iPhone and the computer you connect from should be in the same WiFi net) will result in printing contents of Documents folder of your app. You can browse it and download the files you are interested in

I hope this will be useful.
Thanks for the advice. I have been programming for 25+ years, but only a week on the iPhone. I'm sure I could figure out the above, but it's WAY too complicated for such a simple thing. I'm sure part of it is A**le security.

Perhaps you or someone else can provide an easier solution. Here's what I'm looking for...

(A) Just during development, I need to be able to look inside the iPhone, if for no other reason, to delete my junk files with junk names that I've created during testing. It would also be nice to be able to inspect file contents back on my desktop, rather than having to modify the app to not only write but also read back the file. [EDIT: per scottiphone at iphonedevsdk dot com, "To get file from the device just use organizer. Select your app in the list and twirl it down. Select and drag the app data to your desktop." This indeed works for READING my test files off the iPhone. It won't working for PUTTING test files onto the iPhone, but I'm not doing that. It also won't work for DELETING junk files off the iPhone. I guess I can just remove the app and reinstall for that... Still need to solve (B) below.]

(B) For release, I need users to have a simple solution for getting the file I wrote back over to there desktop. I've seen many existing iPhone apps for that. I was thinking of Readdle Docs. That *would* require my customers to also get another [paid] app. On the other hand, if I went through your suggestion, miniceasar, or perhaps some other that integrated the support into my app itself, then hopefully my customers could much more easily get their data from the iPhone to the desktop. [EDIT: I'm looking into http://groups.google.com/group/diddyFtpServer at the moment, to include FTP capability into my App for this purpose.] [EDIT: Learning further. diddyFtpServer uses GNU GPL, which seems problematic with apple's developer agreement. Looking back at maniceasar's mongoose suggestion, which uses MIT license, which appears for now compatible with apple and iPhone; note I've found comments about BSD license being better than MIT license.] [EDIT: Looks like maniceasar's "here" link is a one-stop-shop with both the wrapper and the mongoose code itself. So other readers of this post can go straight to his third line.]

-Helmut

Last edited by Helmut Forren; 02-08-2010 at 04:56 PM. Reason: found partial answer to (A) and (B)
Helmut Forren is offline   Reply With Quote
Old 02-08-2010, 05:17 PM   #6 (permalink)
Registered Member
 
Join Date: Feb 2010
Posts: 4
Default

Maniceasar,

Thanks very much for the mongoose suggestion. It's looking better and better.

If I do the mongoose thing, I'm sure that it will work using an iPhone WiFi connection that eventually reaches a PC.

If there's no WiFi around, will it work through the iPhone USB? I'm concerned it won't because I've read that apple doesn't give developers USB access.

If it will only work via WiFi, do you know if one can do an [adhoc WiFi network] between a laptop with WiFi and the iPhone, but with NO access point like my Linksys devices in my office? If not, then my users will have to carry not only a laptop, but also an access point. (I may be using the wrong word when I say 'access point'. I have a linksys wireless router in my office.)

Thanks,
Helmut
Helmut Forren is offline   Reply With Quote
Old 02-10-2010, 03:53 AM   #7 (permalink)
Registered Member
 
manicaesar's Avatar
 
Join Date: Feb 2009
Location: Poznań, Poland
Age: 25
Posts: 103
Default

Quote:
Originally Posted by Helmut Forren View Post
Maniceasar,

Thanks very much for the mongoose suggestion. It's looking better and better.

If I do the mongoose thing, I'm sure that it will work using an iPhone WiFi connection that eventually reaches a PC.

If there's no WiFi around, will it work through the iPhone USB? I'm concerned it won't because I've read that apple doesn't give developers USB access.

If it will only work via WiFi, do you know if one can do an [adhoc WiFi network] between a laptop with WiFi and the iPhone, but with NO access point like my Linksys devices in my office? If not, then my users will have to carry not only a laptop, but also an access point. (I may be using the wrong word when I say 'access point'. I have a linksys wireless router in my office.)

Thanks,
Helmut
Well, Apple has just accepted our application update with mongoose server added. In new version of the application, using mongoose, user can both upload and download particular files within application documents folder (not all of course, only those, which we allow to be downloaded). But achieving this is not as simple as viewing application documents folder contents...
If you are interested in how it works, download SuperMemo app (it's free), go to New Exercise menu, click '+' in topright corner and choose Import / Export, then just follow the information listed.

I'm afraid, that you are right with the USB issue :/

And concerning AdHoc WiFi: in work I use iMac, which is connected to the internet via LAN, not WiFi. So I can use iMac's AirPort to share this internet connection, which results in creating local WiFi net. Then i just connect to this WiFi with iPhone. I'm not sure if you can do similar thing on your laptop (if it is MacBook - probably yes , but why don't give it a try?

Hope this helps,
Regards
__________________
Do you like Age Of War? Have you played 'The Wars' and are not fully satisfied? Try Empires At War - we bet you will love it!


------------------
Full Version
------------------
Lite Version
------------------
YouTube Game Trailer
manicaesar is offline   Reply With Quote
Old 11-17-2010, 01:51 PM   #8 (permalink)
jwd
Registered Member
 
Join Date: Nov 2010
Posts: 1
Default Using Mongoose server on an iPhone to upload files back to documents folder

Quote:
Originally Posted by manicaesar View Post
Well, Apple has just accepted our application update with mongoose server added. In new version of the application, using mongoose, user can both upload and download particular files within application documents folder (not all of course, only those, which we allow to be downloaded). But achieving this is not as simple as viewing application documents folder contents...
If you are interested in how it works, download SuperMemo app (it's free), go to New Exercise menu, click '+' in topright corner and choose Import / Export, then just follow the information listed. ...
Hello Manicaesar,

This was some great information as I recently just discovered the Mongoose server and am incorporating it into our iPhone app to both download and upload files within the application documents folder. Found this post and was interested in just how I you modified the Mongoose server to upload files back to the iPhone documents folder. I already have the Mongoose server in place in our app for browsing/downloading files from the documents folder. Could you share your source on performing the upload using Mongoose?

Thank you!
jwd is offline   Reply With Quote
Old 11-18-2010, 08:57 AM   #9 (permalink)
Registered Member
 
manicaesar's Avatar
 
Join Date: Feb 2009
Location: Poznań, Poland
Age: 25
Posts: 103
Default

Quote:
Originally Posted by jwd View Post
Hello Manicaesar,

This was some great information as I recently just discovered the Mongoose server and am incorporating it into our iPhone app to both download and upload files within the application documents folder. Found this post and was interested in just how I you modified the Mongoose server to upload files back to the iPhone documents folder. I already have the Mongoose server in place in our app for browsing/downloading files from the documents folder. Could you share your source on performing the upload using Mongoose?

Thank you!
Hi,
I received your email send to GuLiMaRo. To handle file and printing forms, that can be then accessed and from where upload can be performed, I use following code:

Code:
- (void) startHTTP:(NSString *)ports {
	
	self.ctx = mg_start();     // Start Mongoose serving thread
	mg_set_option(ctx, "root", [DOCUMENTS_FOLDER UTF8String]);  // Set document root
	mg_set_option(ctx, "ports", [ports UTF8String]);    // Listen on port XXXX
	port = [ports copy];
	
	del = self.delegate;
	// Setup URI handler
	// Do not set the handler to have the possibility to browse all application files
	mg_set_uri_callback(ctx, "*", &newUploadForm, NULL);
	mg_set_upload_finished_callback(ctx, &uploadFile, NULL);
	
	// Now Mongoose is up, running and configured.
	// Serve until somebody terminates us
	DLog(@"Mongoose Server is running on http://%@:%@", [self localIPAddress], port);
}
This method is an excerpt of code which can be found here: https://github.com/face/MongooseDaemon.

Then, I implement two functions (pointers to which are used in the above method)

Code:
void uploadFile(struct mg_connection *conn, const struct mg_request_info *info, void *user_data) {
	
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	NSString *postDataString = [NSString stringWithUTF8String:info->post_data];

	//do sth with the string

	[pool drain];
}
and

Code:
void newUploadForm(struct mg_connection *conn, const struct mg_request_info *info, void *user_data) {

	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

	//Create your upload form here (you can use mg_printf function multiple times)
	mg_printf("<html><body><p>GuLiMaRo</p><form name=\"input\" enctype=\"multipart/form-data\" method=\"post\"><input type=\"file\" name=\"upfile\"><br/><input type=\"submit\" value=\"Submit\"></form></body><html>");

	[pool drain];	
}
Please note, that these are C functions, not Objective-C methods - that's why you have to provide autorelease pools, if you use Objective-C objects inside these functions.
__________________
Do you like Age Of War? Have you played 'The Wars' and are not fully satisfied? Try Empires At War - we bet you will love it!


------------------
Full Version
------------------
Lite Version
------------------
YouTube Game Trailer
manicaesar is offline   Reply With Quote
Old 01-22-2011, 12:40 AM   #10 (permalink)
Registered Member
 
Join Date: Dec 2010
Posts: 129
Default

Hi Manicaesar,

Thanks for your big contribution first!!

Currently I am developing an application that users can create Photo albums with my app, can I want to add a function that : Once the wifi of iPhone is connected, user can access all the photo album with a computer on the same network (by typing 192.168.2.1:8080).

So far, with mongoose, I can only visit the document folder of my app. Therefore, could you give me some advice on how can I change the "target path" so that I can access the Photo album and those photos inside (which are store with Core data)

Since I am very new to iPhone dev. , I hope that you give me a hand and I will appreciate it =]

Matthew
From Hong Kong
tmxmatthew is offline   Reply With Quote
Old 01-22-2011, 12:54 AM   #11 (permalink)
Scan Me !
 
MozyMac's Avatar
 
Join Date: Nov 2009
Posts: 590
Send a message via AIM to MozyMac Send a message via MSN to MozyMac Send a message via Yahoo to MozyMac
Default

just a side note: please use the [code] tag when pasting code
MozyMac is offline   Reply With Quote
Old 01-22-2011, 02:44 AM   #12 (permalink)
Registered Member
 
manicaesar's Avatar
 
Join Date: Feb 2009
Location: Poznań, Poland
Age: 25
Posts: 103
Default

Quote:
Originally Posted by tmxmatthew View Post

So far, with mongoose, I can only visit the document folder of my app. Therefore, could you give me some advice on how can I change the "target path" so that I can access the Photo album and those photos inside (which are store with Core data)
I assume you do not set the uri callbacks, so that Documents folder is printed. Look into mongoose.c file for functions: analyze_request() and send_directory() (I skipped the parameters). The first is called when the server receives a request from web browser. There are several if-elses in this function. If the callbacks are not set, within this function, send_directory() is called. You could try modifying the code of mongoose.c so that path parameter passed to send_directory is sth different.

I have no other ideas how to access the Photo album and unfortunately yet no experience in Core Data.
__________________
Do you like Age Of War? Have you played 'The Wars' and are not fully satisfied? Try Empires At War - we bet you will love it!


------------------
Full Version
------------------
Lite Version
------------------
YouTube Game Trailer
manicaesar is offline   Reply With Quote
Old 01-22-2011, 04:26 AM   #13 (permalink)
Registered Member
 
Join Date: Dec 2010
Posts: 129
Default

Quote:
Originally Posted by manicaesar View Post
I assume you do not set the uri callbacks, so that Documents folder is printed. Look into mongoose.c file for functions: analyze_request() and send_directory() (I skipped the parameters). The first is called when the server receives a request from web browser. There are several if-elses in this function. If the callbacks are not set, within this function, send_directory() is called. You could try modifying the code of mongoose.c so that path parameter passed to send_directory is sth different.

I have no other ideas how to access the Photo album and unfortunately yet no experience in Core Data.
It is okay and many thanks to your advice. =]
tmxmatthew is offline   Reply With Quote
Reply

Bookmarks

Tags
initwithcontentsoffile, nsfilehandle, writedata

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



» Advertisements
» Stats
Members: 158,481
Threads: 89,092
Posts: 380,127
Top Poster: BrianSlick (7,091)
Welcome to our newest member, paverlight
Powered by vBadvanced CMPS v3.1.0

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