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];
}
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];
Related
I desperately need to show a progress bar or an activity indicator , because image uploading takes time. Below is my code, I cannot figure it out why progress bar is not showing. I have used ProgressHUD.
[ProgressHUD show:#"Please wait..."];
NSDictionary *params =#{ #"name":self->Name.text, #"contact_no":self->ContactNo.text,#"email_id":self->EmailId.text,#"s_date":Date,#"s_time":Time,#"streat":Street,#"city":City,#"state":State};
NSData *uploadData = Data;
NSString *urlString = [NSString stringWithFormat:#"http://fsttest.com/iosservice/supremo/add_supremo"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSString *kNewLine = #"\r\n";
NSMutableData *body = [NSMutableData data];
for (NSString *name in params.allKeys) {
NSData *values = [[NSString stringWithFormat:#"%#", params[name]] dataUsingEncoding:NSUTF8StringEncoding];
[body appendData:[[NSString stringWithFormat:#"--%#%#", boundary, kNewLine] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"", name] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#%#", kNewLine, kNewLine] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:values];
[body appendData:[kNewLine dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"file_name\"; filename=\"test\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:uploadData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
choice 1
as your way continution add the delegate and check like
- (void)connection:(NSURLConnection *)connection
didSendBodyData:(NSInteger)bytesWritten
totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
float progress = [[NSNumber numberWithInteger:totalBytesWritten] floatValue];
float total = [[NSNumber numberWithInteger: totalBytesExpectedToWrite] floatValue];
NSLog(#"progress/total %f",progress/total);
}
choice 2
modify your request from sendSynchronousRequest to sendAsynchronousRequest for e,g
// NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
call the method like
// set URL
[request setURL:[NSURL URLWithString:baseUrl]];
// add your progress bar here
[ProgressHUD show:#"Please wait..."];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
[ProgressHUD dismiss];
if ([httpResponse statusCode] == 200) {
NSLog(#"success");
if ([data length] > 0 && error == nil)
[delegate receivedData:data];
// hide the progress bar here
}
}];
You can use AFNetworking for easily upload image. here click on AFNeworking Download. Same as your code upload images.
-(void)imageUpload
{
#try
{
[self progressViewDispaly];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager.requestSerializer setTimeoutInterval:600.0];
[manager POST:YOUR_WEB_SERVICE_NAME parameters:YOUR_REQUEST_PARA constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData)
{
for(NSString *strImageName in ImageArray) //if multiple images use image upload
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:strImageName];
if (path != nil)
{
NSData *imageData = [NSData dataWithContentsOfFile:path];
[formData appendPartWithFileData:imageData name:[NSString stringWithFormat:#"job_files[]"] fileName:[NSString stringWithFormat:#"%#",[[strImageName componentsSeparatedByString:#"/"] lastObject]] mimeType:#"image/jpeg"];
}
else
{
}
}
} progress:^(NSProgress * _Nonnull uploadProgress)
{
[self performSelectorInBackground:#selector(makeAnimation:) withObject:[NSString stringWithFormat:#"%f",uploadProgress.fractionCompleted]];
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
{
[SVProgressHUD dismiss];
[_progressView removeFromSuperview];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
} #catch (NSException *exception)
{
NSLog(#"%#",exception.description);
}
}
-(void)makeAnimation:(NSString *)str
{
float uploadProgress = [str floatValue];
[_progressView setProgress:uploadProgress];
}
-(void)progressViewDispaly
{
UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:#"statusBarWindow"] valueForKey:#"statusBar"];
_progressView = [[UIProgressView alloc] init];//WithProgressViewStyle:UIProgressViewStyleBar];
_progressView.frame = CGRectMake(0, 0, CGRectGetWidth(statusBar.frame),20);
_progressView.backgroundColor = [UIColor blueColor];
_progressView.progressTintColor = [UIColor whiteColor];
[statusBar addSubview:_progressView];
}
I am trying to send a post request.
Here is my try:
-(void)Test{
NSDictionary * orderMasterDict = #{#"distributorId":#10000,
#"fieldUsersId": #3,
#"itemId":#0,#"orderMatserId":#56358 };
Globals.OrderDetailsArray = [NSMutableArray arrayWithObjects:orderDetailsDictAnatomy,orderDetailsDictTexture,orderDetailsDictTranslucency, nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:Globals.OrderDetailsArray options:NSJSONWritingPrettyPrinted error:nil];
NSData *postData2 = [NSJSONSerialization dataWithJSONObject:orderMasterDict options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString2 = [[NSString alloc] initWithData:postData2 encoding:NSUTF8StringEncoding];
NSString *jsonString = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:jsonString2 forKey:#"orderMaster"];
[_params setObject:jsonString forKey:#"orderDetails"];
[_params setObject:[NSString stringWithFormat:#"3"] forKey:#"userId"];
[_params setObject:[NSString stringWithFormat:#"ALRAISLABS"] forKey:#"subsCode"];
// 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 = #"imageUpload";
// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:#"http://192.168.0.102:8080/Demo/Test/create"];
// 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(_uploadImageView.image, 0.6);
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]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// set URL
[request setURL:requestURL];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error){
NSLog(#"ERROR :",error);
}else{
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(#"response status code: %ld", (long)[httpResponse statusCode]);
if ([httpResponse statusCode] == 200) {
NSLog(#"StatusCode : %ld",(long)[httpResponse statusCode]);
}else{
NSLog(#"Error");
}
}
}] resume];}
How to make a multipartFormData request?
I tried googling for it, couldn't find any answer suitable for this situation, and thought well .Please help me finding the right solution.
Thanks in advance.
First you change your image in NSData then help of AFNetworking you can post your image.
NSData *data = UIImagePNGRepresentation(yourImage);
imageData = [data base64EncodedStringWithOptions: NSDataBase64Encoding64CharacterLineLength];
Then use this code:
NSMutableDictionary *finaldictionary = [[NSMutableDictionary alloc] init];
[finaldictionary setObject:imageData forKey:#"image"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST: [NSString stringWithFormat: #"%#%#", IQAPIClientBaseURL, kIQAPIImageUpload] parameters: finaldictionary constructingBodyWithBlock: ^(id<AFMultipartFormData> formData) { }
progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"Success response=%#", responseObject);
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData: responseObject options: NSJSONReadingAllowFragments error: nil];
NSLog(#"%#", responseDict);
}
failure: ^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"Errorrrrrrr=%#", error.localizedDescription);
}
];
By using Alamofire
-(void)CreateOrder{
NSString * urlString = [NSString stringWithFormat:#"YOUR URL"
NSDictionary * orderMasterDict = #{#"distributorId":stakeholderID,
#"fieldUsersId": userID,
#"itemId":#0,#"orderMatserId":#0 };
Globals.OrderDetailsArray = [NSMutableArray arrayWithObjects:orderDetailsDictAnatomy,orderDetailsDictTexture,orderDetailsDictTranslucency, nil];
NSDictionary * consumerDetails = #{#"consumerName":Globals.PatientName,#"consumerReferenceId":Globals.PatientID,#"notes":Globals.PatientNotes,#"cunsumerContacNumber":#"456464654654"};
NSData *postData = [NSJSONSerialization dataWithJSONObject:Globals.OrderDetailsArray options:NSJSONWritingPrettyPrinted error:nil];
NSData *postData2 = [NSJSONSerialization dataWithJSONObject:orderMasterDict options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString2 = [[NSString alloc] initWithData:postData2 encoding:NSUTF8StringEncoding];
NSString *jsonString = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
//retrieving userId from UserDefaults
prefs = [NSUserDefaults standardUserDefaults];
NSString * userIdString = [prefs stringForKey:#"userID"];
NSDictionary *parameters = #{#"orderMaster": jsonString2, #"orderDetails" : jsonString ,#"userId" : userIdString,#"subsCode" : #"ABC_MDENT"};
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//For adding Multiple images From selected Images array
int i = 0;
for(UIImage *eachImage in selectedImages)
{
UIImage *image = [self scaleImage:eachImage toSize:CGSizeMake(480.0,480.0)];
NSData *imageData = UIImageJPEGRepresentation(image,0.3);
[formData appendPartWithFileData:imageData name:#"imageUpload" fileName:[NSString stringWithFormat:#"file%d.jpg",i ] mimeType:#"image/jpeg"];
i++;
}
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
dispatch_async(dispatch_get_main_queue(), ^{
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
NSLog(#"responseObject : %#",responseObject);
if (error) {
NSlog(#"error")
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if ([httpResponse statusCode] == 200) {
resposeStatusCode = [responseObject objectForKey:#"statusCode"];
}else{
NSLog(#"requestError");
}
}
}];
[uploadTask resume]; }
I want to Upload an image and in my code it is uploading correctly, But I want to send one user id along with the image in post, Please some one can explain.
I want to Upload an image and in my code it is uploading correctly, But I want to send one user id along with the image in post, Please some one can explain.
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.profileImageView.layer.cornerRadius = self.profileImageView.frame.size.width / 2;
self.profileImageView.clipsToBounds = YES;
dic= [[NSMutableDictionary alloc]init];
NSUserDefaults *defaults10 = [NSUserDefaults standardUserDefaults];
NSData *imageData = [defaults10 dataForKey:#"image"];
UIImage *contactImage = [UIImage imageWithData:imageData];
profileImageView.image = contactImage;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
id1 = [defaults objectForKey:#"ID"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)Pictureupload:(id)sender
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init] ;
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentModalViewController:picker animated:YES];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
// profileImageView.image = image;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
NSDate *currentDate = [[NSDate alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSString *localDateString = [dateFormatter stringFromDate:currentDate];
NSString* cleanedString = [[localDateString stringByReplacingOccurrencesOfString:#"." withString:#""]stringByReplacingOccurrencesOfString:#":" withString:#""];
NSString *cleanedString2 = [cleanedString stringByAppendingFormat:#"%d",1];
NSString *finalUniqueImageNAme ;
finalUniqueImageNAme = [cleanedString2 stringByAppendingString:#".jpg"];
NSData *imageData = UIImageJPEGRepresentation(image, 90);
NSString *urlString = #"http://vygears.com/tcdc-portfolio/Abdul/chat/Pupload_file.php";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"file\"; filename=\"%#\"\r\n",finalUniqueImageNAme] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Successfully uploaded");
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(conn)
{
NSLog(#"Connection Successful");
[self dismissModalViewControllerAnimated:true];
}
else
{
NSLog(#"Connection could not be made");
}
});
});
[picker dismissModalViewControllerAnimated:YES];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
webdata =[[NSMutableData alloc]init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[webdata appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"%#",error);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
// NSString *responseString = [[NSString alloc]initWithData:webdata encoding:NSUTF8StringEncoding];
dic=[NSJSONSerialization JSONObjectWithData:webdata options:0 error:nil];
NSLog( #"Success %#",dic);
NSString * res = [dic objectForKey:#"url"];
NSURL *imageURL = [NSURL URLWithString:res];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
// Update the UI
self.profileImageView.image = [UIImage imageWithData:imageData];
NSUserDefaults *defaults10 = [NSUserDefaults standardUserDefaults];
[defaults10 setObject:imageData forKey:#"image"];
[defaults10 synchronize];
});
});
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissModalViewControllerAnimated:YES];
}
I have done like this now it is working fine.
// ----------------------------------Upload Image --------
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"file\"; filename=\"%#\"\r\n",finalUniqueImageNAme] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// ----------------------------------Passing user_id in Post--------
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"user_id\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:id1] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Successfully uploaded");
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
While capturing image from phone camera and uploading to server, app get crashed and getting this error:
[/BuildRoot/Library/Caches/com.apple.xbs/Sources/CoreUI/CoreUI-371.4/Bom/Storage/BOMStorage.c:522] <memory> is not a BOMStorage file
2016-02-19 10:31:53.413 Appname[520:141128] Received memory warning.
Message from debugger: Terminated due to memory issue.
Code:
UIImage *finalImage, *rotatedImage;
finalImage = self.capturedimg;
if (finalImage.imageOrientation == UIImageOrientationRight)
{
rotatedImage = [self imageRotatedByDegrees:finalImage deg:90];
}else if (finalImage.imageOrientation == UIImageOrientationDown)
{
rotatedImage = [self imageRotatedByDegrees:finalImage deg:180];
}else if (finalImage.imageOrientation == UIImageOrientationLeft)
{
rotatedImage = [self imageRotatedByDegrees:finalImage deg:-90];
}else if (finalImage.imageOrientation == UIImageOrientationUp)
{
rotatedImage = [self imageRotatedByDegrees:finalImage deg:360];
}
imageView.image = rotatedImage;
-(void)sendImage:(id)sender{
CGFloat compression = 0.5f;
CGFloat maxCompression = 0.1f;
int maxFileSize = 250*1024;
imageData = UIImageJPEGRepresentation(imageView.image, compression);
while ([imageData length] > maxFileSize && compression > maxCompression)
{
compression -= 0.1;
imageData = UIImageJPEGRepresentation(imageView.image, compression);
}
NSString *dateString = [self.serviceConnector datenow];
NSString *urlString = [NSString stringWithFormat:#"%#",SinglechatImageUpload_Url];
[allObjectArray removeAllObjects];
NSDictionary *tempDict = [NSDictionary dictionaryWithObjectsAndKeys:
// Object and key pairs
dateString, #"imageuploaddate",
self.CaptionTxtfield.text, #"imagecaption",
nil];
[allObjectArray addObject:tempDict];
[self chatimgUrlString:urlString postValue:allObjectArray imageData:imageData];
}
- (void)chatimgUrlString:(NSString*)urlStr postValue:(NSMutableArray*)array imageData:(NSData*)imgData{
NSString *jsonString;
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array
options:NSJSONWritingPrettyPrinted
error:&error];
if (!jsonData) {
NSLog(#"Got an error: %#", error);
} else {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#",urlStr]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:10];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"userfile\"; filename=\".jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imgData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//json sting parameter
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"jsonstring\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
receivedData = nil;
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
receivedData = [[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
receivedData = nil;
connection = nil;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
#try {
//send the data to the delegate
id jsonObjects = [NSJSONSerialization JSONObjectWithData:reciveddata options:NSJSONReadingMutableContainers error:nil];
NSLog(#"json : %#",jsonObjects);
}
#catch (NSException *exception) {
NSLog(#"Exception error didfinishload: %#",exception.reason);
receivedData = [[NSMutableData alloc]init];
[self.delegate requestReturnedData:receivedData];
}
}
Try to add Autoreleasepool block in your while loop:
while ([imageData length] > maxFileSize && compression > maxCompression)
{
#autoreleasepool {
compression -= 0.1;
imageData = UIImageJPEGRepresentation(imageView.image, compression);
}
}
Hi i am very beginner in Ios and in my project i need to send "Username" and "Password" and "UserImage" to server using NSURLConnection and for this i have inserted this three fields(username,password,userimage) in one Dictionary and i am posting this dictionary to server but using my below code details are not sending to server please help me what did i do here wrong
my code:-
#interface SendingImagesToServer ()
{
NSMutableData *body;
}
#end
#implementation SendingImagesToServer
- (void)viewDidLoad {
[super viewDidLoad];
NSData *imageData;
UIImage * image;
NSError *error = nil;
image = [UIImage imageNamed:#"friendship.jpg"];
imageData = UIImageJPEGRepresentation(image, 0.1f);
NSDictionary *mainDict = [NSDictionary dictionaryWithObjectsAndKeys:
#"James" ,#"username",
#"1234",#"Password",
imageData,#"image",
nil];
NSString *jsonString = [mainDict JSONRepresentation];
NSData * webbody = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
body = [webbody mutableCopy];
NSString *urlstr = [NSString stringWithFormat:#"My url here"];
NSURL *url = [NSURL URLWithString:urlstr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"----WebKitFormBoundarycC4YiaUFwM44F6rT";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"imagename\"; filename=\"picture.png\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
if(imageData == nil && error!=nil) {
NSLog(#"nil");
}
else
{
NSLog(#"not nill");
}
[body appendData:[#"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Successfully sending to server");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"error is %#",[error localizedDescription]);
}
#end
You create the request, but don't start it anywhere in your code. Also you don't create the NSURLConnection anywhere (at least not in the posted part).
The easiest way to achieve this would be to simply add this line at the end of your viewDidLoad method :
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
You can read more here