PDA

View Full Version : It can't be that hard: NSData & NSString




bbarnhart
Jun 27, 2007, 07:28 PM
I've resurrected an old Cocoa project and after making some additions I'm still stuck on something that caused me to stop in the first place. I'm still learning Cocoa so I may not quite "get it" yet, but this can't be that hard.

I've got a xml file I want to upload to my web server. I want to add some data before the xml data. Basically, my url looks like this:

http://../myphp.php?type=Put&file=xxx.xml&data=<xmldata here>

So, I've tried building an NSString to put "type=Put&file=xxx.xml&data=" and then copy that into an NSMutableData object. Then I add the xml to the NSMutableData. I had it "working" once, but then it failed with a different xml file.

Am I making a mistake with Unicode or am I not understanding fully how NSString and NSMutableData works? Any help would be appreciated!


- (void) makeXML
{
...
NSXMLDocument* xmlDoc = [[NSXMLDocument alloc] initWithRootElement:root];
NSData *xmlData = [xmlDoc XMLDataWithOptions:NSXMLNodePrettyPrint];

[xmlData writeToFile:@"/Users/b...barnhart/Temp/hello.xml" atomically:YES];

[self uploadTest: xmlData];

return TRUE;
}

- (void) uploadTest: (NSData*) data
{
NSURL* webServiceURL = [NSURL URLWithString:@"http://.../~b...barnhart/.../xxxxxx.php"];
NSMutableURLRequest* urlRequest = [NSMutableURLRequest requestWithURL:webServiceURL];

NSString* str = @"type=Put&filename=xxx.xml&data=";
const char* utf_str = [str UTF8String];
NSMutableData* mute_data = [NSMutableData dataWithLength:strlen(utf_str) + [data length]];
[mute_data appendBytes:utf_str length:strlen(utf_str)];
[mute_data appendData:data];

... stops working down here, but I think the problem is above

}



kainjow
Jun 27, 2007, 07:47 PM
The best way to go from NSString to NSData is via NSString's dataUsingEncoding:allowLossyConversion: method, and you usually want NSUTF8StringEncoding as the encoding.