0

I would like to post data on server with single URL which contains voice data, image and some text parameters using NSMutableURLRequest and NSURLConnection delegate.

Thanks in advance.

NSString *dvcToken = [[NSUserDefaults standardUserDefaults] valueForKey:@"deviceToken"];
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
// parameters to send
[_params setObject:@"842" forKey:@"office"];
[_params setObject:@"8442" forKey:@"client"];
[_params setObject:@"0" forKey:@"sub"];
[_params setObject:ofcrName forKey:@"name"];
[_params setObject:ofcrNo forKey:@"number"];// cin_out_datetime
[_params setObject:curntDateTime forKey:@"cin_out_datetime"];
if(logIn){
    [_params setObject:@"I" forKey:@"process_type"];
    logIn = false;
}else
    [_params setObject:@"0" forKey:@"process_type"];
[_params setObject:dvcToken forKey:@"device_imei"];
[_params setObject:[[UIDevice currentDevice] name] forKey:@"device_name"];
//[_params setObject:audioData forKey:@"voice"];


// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
NSString *BoundaryConstant = @"----------V2ymHFg03ehbqgZCaKO6jy";

// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ
NSString* FileParamConstant = @"file";

// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:@"https://myUrl"];

// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:@"POST"];

// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];

// post body
NSMutableData *body = [NSMutableData data];

// add params (all params are strings)
for (NSString *param in _params) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}

// add image data
NSData *imageData = UIImageJPEGRepresentation(officerImage, 1.0);
if (imageData) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:imageData];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}

[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];

// my audio to post
NSString *audioUrl = [NSString stringWithContentsOfURL:player.url];
NSData *audiodata;
audiodata = [[NSData alloc] initWithContentsOfFile:audioUrl];
// add it to body
[body appendData:audiodata];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

// final boundary
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];


// setting the body of the post to the reqeust
[request setHTTPBody:body];

// set the content-length
NSString *postLength = [NSString stringWithFormat:@"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

// set URL
[request setURL:requestURL];
Pawan Rai
  • 3,434
  • 4
  • 32
  • 42
vaibhav
  • 4,038
  • 1
  • 21
  • 51
  • Post your code here and point out where you are having issue. – Pawan Rai May 05 '16 at 11:37
  • i am following this post: [link](http://stackoverflow.com/questions/8564833/ios-upload-image-and-text-using-http-post) where i am finding a way to send my voice data also kindly suggest. – vaibhav May 05 '16 at 11:57
  • That post works perfectly, where you are having issue in your code post it here in your question. – Pawan Rai May 05 '16 at 12:00
  • when i am adding my audio data to post gives me server side error ..where without audio data working perfect. – vaibhav May 05 '16 at 12:27
  • What's the server side error, post it here as well.that will help in identifying the issue if it is server side or mobile app. – Pawan Rai May 05 '16 at 13:26
  • the error i am getting > "JSONValue failed. Error is: Illegal start of token [<]" kindly see the code where i am trying to add my audio data inside the body ..i think the problem is there. Thanks – vaibhav May 06 '16 at 07:11
  • Did you check if player.url return you valid data. I think you should have audio file path here if your audio file is in local. [[NSData alloc] initWithContentsOfURL:[NSURL fileURLWithPath:localFilePath]]; – Pawan Rai May 06 '16 at 08:06

1 Answers1

0

you can use this method

-(NSMutableURLRequest *)setSingleFileMultipartRequestForUserID:(NSString *)userID serverUrl:(NSString *)url fileData:(NSData *)fileData fileName:(NSString *)fileName MIMEType:(NSString *)mimeType
    {
        NSMutableURLRequest *serverRequest = nil;

        if(userID != nil || ![[NSString stringWithFormat:@"%@",userID] isEqualToString:@""] || url != nil || ![url isEqualToString:@""] || fileData.length >4)
        {
            NSURL *URL                         = [NSURL URLWithString:url];
            NSString * lineEnd = @"\r\n";
            NSString * twoHyphens = @"--";
            NSString * boundary = [[NSUUID UUID] UUIDString];
            NSData *voiceData = nil;
            voiceData = fileData;
            if(voiceData != nil)
            {
                serverRequest = [[NSMutableURLRequest alloc] init];
                [serverRequest setTimeoutInterval:50];
                [serverRequest setURL:URL];
                [serverRequest setHTTPMethod:@"POST"];
                [serverRequest addValue:[NSString stringWithFormat:@"%@",userID] forHTTPHeaderField:@"user_id"];
                [serverRequest addValue:mimeType forHTTPHeaderField:@"mime-Type"];
                [serverRequest addValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary] forHTTPHeaderField:@"Content-Type"];
                NSMutableData *bodyData = [[NSMutableData alloc] init];
                [bodyData appendData:[[NSString stringWithFormat:@"%@%@%@",twoHyphens, boundary,lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
                [bodyData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data;  name=\"uploaded_file\"; filename=%@ %@",[fileName stringByReplacingOccurrencesOfString:@" " withString:@"_"],lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
                [bodyData appendData:[[NSString stringWithFormat:@"%@", lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];

                [bodyData appendData:voiceData];

                [bodyData appendData:[[NSString stringWithFormat:@"%@", lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
                [bodyData appendData:[[NSString stringWithFormat:@"%@%@%@%@",twoHyphens, boundary,twoHyphens, lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
                [serverRequest setHTTPBody:bodyData];
            }
        }
        return serverRequest;
    }

it returns NSMutableURLRequest object

then use this object for request

 NSURLRequest * urlRequest2 = NSMutableURLRequest //requset get by above method
   NSURLResponse * response2 = nil;
            NSError * error2 = nil;



    NSData * data2 = [NSURLConnection sendSynchronousRequest:urlRequest2
                                                       returningResponse:&response2
                                                                   error:&error2];

 if (error2 == nil)
            {

                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];
}
balkaran singh
  • 2,754
  • 1
  • 17
  • 32