1

After recording with AVAudioRecorder the resulting sound file has to be sent to a webservice. The file data has to be URL encoded and copied into the body of the POST request. The recording format is kAudioFormatAppleLossless. As a first step, prior to URL encoding, I tried to copy the .caf file into a NSString, using

NSStringEncoding encoding;
 NSString * filestring = [NSString 
                         stringWithContentsOfURL:self.audioRecorder.url 
                     usedEncoding:&encoding 
                         error:&error];

I got the following error:

Error Domain=NSCocoaErrorDomain Code=264 "The operation couldn\u2019t be completed. (Cocoa error 264.)"

The encoding returned was 0x5bab9f0, which is not among the list of values defined for NSStringEncoding. What encoding does AVAudioRecorder use when writing to the file? What is the best way of converting a binary file to a URL encoded string?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
primulaveris
  • 966
  • 14
  • 20

1 Answers1

3

Never. Use. NSString. For. Data. That's. Not. A. String... Use NSData instead, you won't need to URLEncode it (because it 'already is').

You can use this:

NSMutableData *postData = [[NSMutableData alloc] init];
[postData appendData:[@"--boundary\r\nContent-Disposition: form-data; name=\"myfile\"; filename=\"ad.gif\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[NSData dataWithContentsOfURL:self.audioRecorder.url]];
[postData appendData:[@"\r\n--boundary--\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

[myRequest setHTTPMethod:@"POST"]; // this you probably already did.
[myRequest setHTTPBody:postData];
cutsoy
  • 10,127
  • 4
  • 40
  • 57
  • The file contents have to be copied into the POST body as a parameter, not sent as form-data. Tried using NSData, but results were not as expected by server, see below: sendFileRequest = [ASIFormDataRequest requestWithURL:myURL]; NSData * data = [NSData dataWithContentsOfURL:audioRecorder.url]; [sendFileRequest setPostValue:data forKey:kParamRecordBinaryContent]; – primulaveris Mar 08 '11 at 16:51
  • Are you requesting the file using $_FILES['myfile']; (in case you're using PHP)? Btw. you *are* using NSURLConnection + NSMutableURLRequest, right? – cutsoy Mar 08 '11 at 18:47
  • 1
    It's going to a webservice. However discovered binary data has to be base64 encoded first for server, so final solution is ' NSString * encodedString = [QSStrings encodeBase64WithData:[NSData dataWithContentsOfURL:audioRecorder.url]];' see also [link](http://stackoverflow.com/questions/392464/any-base64-library-on-iphone-sdk) Thanks very much for your help – primulaveris Mar 09 '11 at 19:58