How to solve received memory warning error? - ios

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);
}
}

Related

How to post multiple images using multipart / formdata in objective c

I am trying to post two images to an url using multipart post request in Objective C , From my code I can able to send only one image, How to send two images to the url, using multipart / form data I have tried so many example for this bur I did not get the result I want
-(void)processPostMultipartRequestNew{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSString *urlStr = [self.dataModel.apiUrl
stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
urlStr = [urlStr
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
urlStr= [urlStr stringByReplacingOccurrencesOfString:#"+" withString:#"%2B"];
NSURL *reqUrl = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:reqUrl];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSDictionary *requestBody = self.dataModel.requestParams2;
UIImage *imageToUpload = [requestBody objectForKey:keyUploadImage];
NSDictionary *requestBody2 = self.dataModel.requestParams;
UIImage *imageToUpload2 = [requestBody2 objectForKey:keyUploadImage];
if(requestBody){
NSData *imageData = UIImageJPEGRepresentation(imageToUpload, 0);//no compression by default
NSData *imageData2 = UIImageJPEGRepresentation(imageToUpload2, 0);
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: attachment; name=\"uploadedfile1\"; filename=\".jpeg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: attachment; name=\"uploadedfile2\"; filename=\".jpeg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[NSData dataWithData:imageData2]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// Text parameter1
NSString *param1 = #"111";
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"SyncId\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:param1] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
}
[request setHTTPShouldHandleCookies:NO];
[request setHTTPMethod:REQUEST_TYPE_POST];
[request setTimeoutInterval:60*4];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSLog(#"completionHandler with response:%#",[NSHTTPURLResponse localizedStringForStatusCode:[(NSHTTPURLResponse*)response statusCode]]);
NSLog(#"reponse: %ld",(long)[(NSHTTPURLResponse*)response statusCode]);
NSInteger status = [(NSHTTPURLResponse*)response statusCode];
if(error){
NSLog(#"http request error: %#", error.localizedDescription);
// handle the error
}
else{
if (status == 201){
// handle the success
}
else{
NSLog(#"error");
} // handle the error
}
if(!data || data == nil)
return ;
NSLog(#"%#",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
NSDictionary *resultDict =(NSDictionary *) [NSJSONSerialization
JSONObjectWithData:data options:NSJSONReadingAllowFragments
error:&error];
//NSDictionary *resultDict =(NSDictionary *) [NSJSONSerialization JSONObjectWithStream:data options:kNilOptions error:&error];
self.dataModel.responseData =resultDict;
NSLog(#"error is %#",error);
NSLog(#"data is %#",data);
{
if(!data || data == nil)
return ;
NSLog(#"%#",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
//for failed case
if(error || error != nil){
self.dataModel.responseFailed = YES;
self.dataModel.error = error;
NSLog(#"Result in error case %#",[[error userInfo] objectForKey:#"NSDebugDescription"]);
[self.reciever performSelectorOnMainThread:self.callBack withObject:self.dataModel waitUntilDone:YES];
}
else{
self.dataModel.responseFailed = NO;
self.dataModel.error = nil;
NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if(!([response rangeOfString:#".jpg"].location==NSNotFound))
{
NSString *res=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
self.dataModel.responseData =res;
[self.reciever performSelectorOnMainThread:self.callBack withObject:self.dataModel waitUntilDone:YES];
}
}
}
self.executing = NO;
[self setFinishedState:YES];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
[self.reciever performSelectorOnMainThread:self.callBack withObject:self.dataModel waitUntilDone:YES];
}];
}
Is this a right way to do? if not how can I get success in this. Thanks in advance.
Yes you can like this
Edit
///////////////////////////////
// Dictionary that holds post parameters. You can set your post parameters that your server accepts or programmed to accept.
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:#"ios" forKey:#"device_type"];
[_params setObject:#"user" forKey:#"type"];
[_params setObject:"iddddd" forKey:#"user_id"];
// 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
// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:#"http........"];
// 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 allKeys]) {
[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 txt data
/////////////////////////////
NSArray *allImagesData= #[UIImagePNGRepresentation(imageToUpload) ,UIImagePNGRepresentation(imageToUpload2)];
NSLog(#"files array before %#", allImagesData);
for (int i=0; i<[allImagesData count]; i++)
{
NSString*filename=[NSString stringWithFormat:#"image%d.jpeg",i+1];
NSString* FileParamConstant = [NSString stringWithFormat:#"image%d",i+1];
NSData *imageData = allImagesData[i];
if (imageData)
{
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"%#\"\r\n", FileParamConstant,filename] 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]];
}
U can do like this:
-(void)PostUrlCall_Multipart_Image:(NSString *)IN_URL Param:(NSDictionary*)IN_Param Image:(UIImage *)image
{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/json"];
[manager POST:IN_URL parameters:IN_Param constructingBodyWithBlock:^(id<AFMultipartFormData> formData){
[formData appendPartWithFileData:UIImageJPEGRepresentation(image, 1.0) name:#"image" fileName:#"image" mimeType:#"image/jpeg"];
}
progress:nil
success:^(NSURLSessionDataTask *task, id responseObject) {
m_Status=1;
self.dic_Response = (NSDictionary *)responseObject;
[[NSNotificationCenter defaultCenter] postNotificationName:m_strPostMsg object:self];
}
failure:^(NSURLSessionTask *operation, NSError *error){
m_Status=0;
self.dic_Response=[[NSMutableDictionary alloc]init];
// [self.dic_Response setValue:#[Time_Out_Msg] forKey:#"#[Time_Out_Msg]"];
NSLog(#"Error %#",error);
[[NSNotificationCenter defaultCenter] postNotificationName:m_strPostMsg object:self];
}];
}

POST image to PHP web service in IOS

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];

Can not show progress bar while uploading image to server

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 want to send user id with image upload in ios

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];

How to send Text and Images to server using NSURLConnection in ios

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

Resources