Search code examples
iosobjective-cnsurlconnectionios7.1

NSUrlConnection executing multiple times


I've uploaded a image using the below code.Image saving 3 times in Web server. I am confusing to make changes in my code.

NSString *url=[NSString stringWithFormat:@"http://192.168.2.4:98/UserImage.svc/InsertFacialImage?%@",requestString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];

// Create 'POST' MutableRequest with Data and Other Image Attachment.

 NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];
NSData *data = UIImageJPEGRepresentation(chosenImage, 0.2f);
[request addValue:@"image/png" forHTTPHeaderField:@"Content-Type"];
NSMutableData *body = [NSMutableData data];


   [body appendData:[NSData dataWithData:data]];
[request setHTTPBody:body];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

NSLog(@"Ret: %@",returnString);

NSURLConnection *connReq = [NSURLConnection connectionWithRequest:request delegate:self];
 if (connReq)
 {

    NSLog(@"Connection Sucessful");
  //  receivedData = [[NSMutableData alloc]init];

}

else {

    NSLog(@"failed");

}

[connReq start];

Solution

  • replace your

    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    with NSData *returnData;

    it'll reduce from 3 to 2.