0

I have made some image views and their button under them. When user select image from gallery it displays on image view. Now I want that image to be sent to server through PHP web service and use POST method. I want it to first convert it to base64 bits.

My code is

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"ddMMyyyyHHmmss"];
    
    NSData *data = UIImageJPEGRepresentation(_img1.image, 1.0);
    UIImage *imagedata = [UIImage imageWithData:data];
    
    NSString * base64String = [data base64EncodedStringWithOptions:0];
    NSDate *now = [[NSDate alloc] init];
    NSString *theDate = [dateFormat stringFromDate:now];
    
    //---------- Compress photo----------
    double compressionRatio = 1;
    int resizeAttempts = 5;
    while ([data length] > 1000 && resizeAttempts > 0)
    {
        resizeAttempts -= 1;
        compressionRatio = compressionRatio*0.6;
        data = UIImageJPEGRepresentation(imagedata,compressionRatio);
        
    }
    
    NSString *baseurl = @"myurl";
    NSURL *dataURL = [NSURL URLWithString:baseurl];
    
    NSMutableURLRequest *dataRqst = [NSMutableURLRequest requestWithURL:dataURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:500.0];
    [dataRqst setHTTPMethod:@"POST"];
    
    NSString *stringBoundary = @"0xKhTmLbOuNdArY---This_Is_ThE_BoUnDaRyy---pqo";
    NSString *headerBoundary = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",stringBoundary];
    
    [dataRqst addValue:headerBoundary forHTTPHeaderField:@"Content-Type"];
    
    NSMutableData *postBody = [NSMutableData data];
    
    // -------------------- ---- image Upload Status -----------------------
    [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image\"; filename=\"%@\"\r\n",[NSString stringWithFormat:@"%@.jpeg",theDate]] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:data];
    [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithFormat:@"--%@--\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [dataRqst setHTTPBody:postBody];
    
    self.conn = [[NSURLConnection alloc] initWithRequest:dataRqst delegate:self];
    
     //SubmitDetailsViewController *presales = [self.storyboard instantiateViewControllerWithIdentifier:@"SubmitDetailsViewController"];
    // [self.navigationController pushViewController:presales animated:YES];

}
#pragma mark NSURLConnection Delegate Methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    self->recieveData = [[NSMutableData alloc] init];
}

//------------- Response from server -------------
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
   [ self->recieveData appendData:data];
    
    NSError* error;
    NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
                                                         options:kNilOptions
                                                           error:&error];
    
}
eglease
  • 2,445
  • 11
  • 18
  • 28
omer
  • 7
  • 6

1 Answers1

1

You can use AFNetworking library to do this. Add AFNetworking to your projec and import AFNetworking.h in to your class and you can then do something like,

  UIImageView *imageView;  // your image view

NSData *imgData = UIImageJPEGRepresentation(imageView.image, 1.0);

NSString *base64ImageStr = [imgData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

NSString *strToSend = [base64ImageStr stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];

NSDictionary *parameters = @{@"yourServerKeyOrParameterForImage" : strToSend};  // you can add other parameters as well

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

[[manager POST:@"your url" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

    NSLog(@"your response : %@",responseObject);

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

    NSLog(@"error : %@",error.localizedDescription);

}]resume];
Ketan Parmar
  • 27,092
  • 9
  • 50
  • 75
  • Do you want to send image as `multipart form data` or as `base64string` ? because your edited question shows try of form data and your earlier question was asking about bas64!!! – Ketan Parmar May 15 '17 at 10:18
  • base64string. @Lion – omer May 15 '17 at 10:20
  • then use my answer! – Ketan Parmar May 15 '17 at 11:31
  • how if i want to send multiple images? @Lion – omer May 16 '17 at 05:26
  • then convert every image in base64String and send array of that strings to server or in whatever format that your server accepts! Basically your server should accept array of images in your case! So in your parameter dictionary you should set array (of string images) instead of single `strToSend` ! – Ketan Parmar May 16 '17 at 05:34
  • my parameters for images are imgurl1,timestamp1,imgurl2,timestamp2 ... . here imgurll1 is image 1 and timestamp1 is time in millisecond that should send to server with it. Now how would i convert it to array? @Lion – omer May 16 '17 at 07:36