3

Hi i am very new for ios and i am trying to send some parameters to server using NSURLSession(they are USERname,USERtype,USERimage) but based on my below code image is not goes to server and how to send images to server please help me where did i do here wrong?

my code:-

    NSError *error;

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
    NSURL *url = [NSURL URLWithString:@"[JSON SERVER"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:60.0];

    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

    [request setHTTPMethod:@"POST"];

   UIImage *myImage = [UIImage imageNamed:@"myImage.png"];
NSString *myImage = [UIImagePNGRepresentation(myImage) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

    NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: @"TEST IOS", @"name",
                         @"IOS TYPE", @"typemap",
                         myImage,@"image"
                         nil];
    NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
    [request setHTTPBody:postData];


    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

    }];

    [postDataTask resume];
AbhiRam
  • 2,033
  • 7
  • 41
  • 94
  • What is the expected format of the image? It is uncommon to send an image within a JSON payload. At the very least, you'll probably have to base64-encode it, though that's inefficient, and of course really depends on what the server is expecting. – jcaron Dec 18 '15 at 10:25
  • .png and jpeg formates – AbhiRam Dec 18 '15 at 12:35
  • i am asking how to send images to server – AbhiRam Dec 18 '15 at 12:38
  • i know how to send text data and i want how to send images to server – AbhiRam Dec 18 '15 at 12:39
  • @AbhiRam I'm not talking about the images themselves, but how they should be encoded. What is the server expecting? You can't just add binary data to a JSON object. So either your server is expecting something other than a JSON object (a `multipart/form-data` submission, for instance), or it's expecting an ID or URL instead of the image itself, or you need to encode the image (in base64 for instance). Do you have control over the server and how it handles the data, or are you supposed to submit using a given specification? – jcaron Dec 18 '15 at 12:49
  • server expecting multipart/form-data submission, how should i change above code as workable code please help me @jcaron – AbhiRam Dec 18 '15 at 12:56
  • There are numerous examples available on the web, a quick search will provide the answer. – jcaron Dec 18 '15 at 13:02
  • i did not get any solutions in web and i have searched lot – AbhiRam Dec 18 '15 at 13:03
  • Possible duplicate of [Uploading Image via POST in Objective C](http://stackoverflow.com/questions/11084403/uploading-image-via-post-in-objective-c/15477035#15477035). @AbhiRam this will help you. – Dipen Panchasara Dec 18 '15 at 13:14
  • What is the problem..?? You haven't specified the problem clearley Is there is any Error? Is your connection is established with server.. You might want to check for NSTrasportkey to use NSUrl in iOS9 and above.. NSTransportkey is we have to add in info.plist file of you project to ask for the permission to connect with internet. otherwise you snippet are looking good.. post the error you got to help you better. – Devang Tandel Dec 18 '15 at 10:18

2 Answers2

0

Try using

UIImage *myImage = [UIImage imageNamed:@"myImage.png"];
NSString *base64Image = [UIImagePNGRepresentation(myImage) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
Vashum
  • 853
  • 1
  • 10
  • 24
-2

You can use AFNetworking library for uploading images. It is more efficient.

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", nil];
    [manager.requestSerializer setValue:[CommonFunctions hmac:sStr withKey:[[NSUserDefaults standardUserDefaults] objectForKey:KEY_ACCESS_TOKEN]] forHTTPHeaderField:@"Signature"];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];

    [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,theFileName] parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
     {
         if (finalImageData)
         {
             [formData appendPartWithFileData:finalImageData name:@"photo" fileName:@"pic.jpg"  mimeType:@"image/jpeg" ];
         }
     } success:^(AFHTTPRequestOperation *operation, id responseObject) {
         NSLog(@"JSON: %@", responseObject);




     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

}
  • 1
    How is AFNetworking more efficient? It uses `NSURLSession` and adds overhead... Also you're providing an example that includes lots of code completely unrelated to the question. – jcaron Dec 18 '15 at 10:24
  • 1
    AFNetworking is easier as compared to NSURLSession. In this you just pass the parameters in a dictionary and append image as byte data. – Mohit Mathur Dec 18 '15 at 10:46