RequestResponse nil I'm getting - ios

I want to pass this data using api. I want to get countryname id,code,but I'm not getting how to do.
-(void) getCountries
{
NSString *get=[[NSString alloc]initWithFormat:#"city id=%#,&lang=%#",[self.countryCode text],[self.countryList textInputMode]];
NSLog(#"postDat :%#",get);
NSURL *url=[NSURL URLWithString:#"http://demo28.know3.com/api/country-list/en.html"];
NSData*postData=[get dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request=[[NSMutableURLRequest alloc]init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"contentLength"];
//[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:postData];
NSError *error=[[NSError alloc]init];
NSHTTPURLResponse *response=nil;
NSData *urldata=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response code %d",(int)[response statusCode]);
if ([response statusCode]<=200 &&[response statusCode]<=300) {
NSString *responseData=[[NSString alloc]initWithData:urldata encoding:NSASCIIStringEncoding];
NSLog(#"Response=%#",responseData);
NSError *error=nil;NSDictionary *jsondata=[NSJSONSerialization JSONObjectWithData:urldata options:NSJSONReadingMutableContainers error:&error];
success=[jsondata[#"success"]integerValue];
NSLog(#"success:%ld",(long)success);
if (success==0) {
NSLog(#"Country");
[self alertStatus:#" country " :#"country List scucess!"];
}else {
NSString *errormsg=(NSString *)jsondata[#"errormesg"];
[self alertStatus:errormsg :#" Failed"];
}
}else{
[self alertStatus:#"connection Failed" :#"sign in failed"];
}
}
-(void)alertStatus:(NSString *)message :(NSString *)title
{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:title message:message delegate:self cancelButtonTitle:#"cancel" otherButtonTitles:nil, nil];
[alert show];
}

Have you tried using AFNetworking? It will make your life much more easier.
Download the code from here AFNetworking
And import the AFNetworking folder to your project.
You can use the following code to get country list in an NSDictionary
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:#"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

Related

How to post data using AFNetworking 2.0 with application/x-www-form-urlencoded HttpHeaderField

I am going to convert NSURLConnection to AFNetworking 2.0. When I use NSURLConnection to post data that works fine. But I have no idea of how to do it with AFNetworking 2.0.
Here is code snip of NSURLConnection request.
#define API_URL #https://myurl.com//login.php"
#define LOGIN_POST_TYPE #"app_data={\"app_data\":{\"user\":\"%#\",\"password\":\"%#\"}}"
+(void) post:(NSString*)api AndPostData:(NSData*)postData AndCallback: (void (^)(id result, NSError *error))callback {
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:API_URL];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setTimeoutInterval:10.0];
[request setHTTPBody:postData];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
NSLog(#"%#",response);
if ([data length] >0 && connectionError == nil)
{
NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
callback([dataStr JSONValue], nil);
}
else
{
callback(nil, connectionError);
}
}];
}
+(void) callAPIWithType:(int)apiType withParams:(NSDictionary *)param andCallback:(void(^)(id result, NSError *error)) callback
{
NSString *strPost = [NSString stringWithFormat:LOGIN_POST_TYPE, param[#"email"], param[#"password"]];
NSLog(#"%#", post);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[self post:API_URL AndPostData:postData AndCallback:^(id result, NSError *error) {
callback(result, error);
}];
}
Like I said, this code works fine. But how do I convert this code to AFNetworking 2.0?
I tried a lot with AFNetworking. But all of ways are not working for me.
I get error response.
What and how can I do?
Heres an example of the code I use, but changed to match your request, your postData just needs to be an NSDictionary not NSData...
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager setRequestSerializer:[AFJSONRequestSerializer serializer]];
[manager POST:#"https://myurl.com//login.php" parameters:postData success:^(AFHTTPRequestOperation *operation, id responseObject) {
// responseObject contains the result
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%# failed: %#",NSStringFromClass([self class]),operation.responseObject);
}];

Image Uploading in iOS

currently i am working on image uploading in ios application and here is my code
AFHTTPRequestOperationManager *man = [[AFHTTPRequestOperationManager alloc]init];
man.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
NSData *imageData = UIImagePNGRepresentation(self.imageView.image);
AFHTTPRequestOperation *op = [man POST:AddGroup parameters:#{ #"userid":#"6",
#"name":self.txtGroupName.text
#"description":self.textViewGroupDescription.text,
#"image":imageData }
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"image" fileName:filename mimeType:#"image/png"];
}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"Success: %# ***** %#", operation.description, operation.responseString);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Imani" message:#"New Group Succesfully Created.." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil] ;
[alertView show];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error: %# ***** %#", operation.responseString, error);
}];
[op start];
now i am getting response from successfully from json but image data are passing null in to server any one have idea ?
Thank you.
try this cede to upload image on server.
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:#"your api link"]];
NSData *imageData = UIImageJPEGRepresentation(self.imgPost.image, 0.5);
NSDictionary *parameters = #{#"param": #"value",
#"param2" : #"value2"
};
AFHTTPRequestOperation *op = [manager POST:#"/api/store/posts/format/json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//do not put image inside parameters dictionary as I did, but append it!
[formData appendPartWithFileData:imageData name:#"file" fileName:[NSString stringWithFormat:#"njoyful_%f.jpg",[NSDate timeIntervalSinceReferenceDate]] mimeType:#"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %# ***** %#", operation.responseString, responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %# ***** %#", operation.responseString, error);
}];
[op start];
I'm not familiar with AFHTTPRequestOperation so i'll just give you something i'm using that creates json request.
- (NSURLRequest *)convertToRequest:(NSString *)stringURL withDictionary:(NSDictionary *)dictionary
{
NSError *error = nil;
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
NSURL *url = [NSURL URLWithString:stringURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: JSONData];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept-Encoding"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[JSONData length]] forHTTPHeaderField:#"Content-Length"];
return request;
}
Please check my answer here
This also work for multi image upload. Cheers! :)

How to use AFNetworking frame work with json Login with my own api i have tokens to pass but i dont now how to use those

How do i use AFNetworking Framework to authenticate and login in to my IPhone application i have my own api and have some tokens like this X-User-Email,X-User-Token. i dont know what i have to do with this tokens somke one help me exactly what i have to do
i am using some code searching many methods but am not getting exactly did i have to do anything more
i have given code like this but i dont know where to give tokens
{
if([[userNameTF text] isEqualToString:#""] || [[passWordTF text] isEqualToString:#""] ) {
[self alertStatus:#"Please enter both Username and Password" :#"Login Failed!"];
} else {
NSString *post =[[NSString alloc] initWithFormat:#"user[email]=%#&user[password]=%#",[userNameTF text],[passWordTF text] ];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:#"http://secure.sample.in/login"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
//[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response code: %d", [response statusCode]);
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#", responseData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
NSLog(#"%#",jsonData);
NSInteger success = [(NSNumber *) [jsonData objectForKey:#"id"] integerValue];
NSLog(#"%d",success);
if(success == 1)
{
NSLog(#"Login SUCCESS");
[self alertStatus:#"Logged in Successfully." :#"Login Success!"];
} else {
NSString *error_msg = (NSString *) [jsonData objectForKey:#"error_message"];
[self alertStatus:error_msg :#"Login Failed!"];
}
} else {
if (error) NSLog(#"Error: %#", error);
[self alertStatus:#"Connection Failed" :#"Login Failed!"];
}
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
[self alertStatus:#"Login Failed." :#"Login Failed!"];
}
Request would like this using AFNetworking :
//Create parameter dictionary
NSDictionary *dictParameters = [NSDictionary dictionaryWithObjectsAndKeys:strEmailHere,#"email",strPasswordHere,#"password",nil];
//create post request
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//pass serializer may be http or json
manager.responseSerializer = [AFHTTPResponseSerializer serializer]; //[AFJSONResponseSerializer serializer];
AFHTTPRequestOperation *apiRequest = [manager POST:strURL parameters:dictNewParameter success:^(AFHTTPRequestOperation *operation, id responseObject)
{
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
}];

Data is Not Getting post on the web service

I want to post Dictionary to a Web service. but it is not getting post .Every time when i post data i am getting error message form web-service. I also try different approach using AFNetworking but using that approach i am getting 406 error.
you can see the other question here
NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
[params setValue:self.txtUserName.text forKey:#"name"];
[params setValue:self.txtEmail.text forKey:#"mail"];
[params setValue:self.txtPass.text forKey:#"conf_mail"];
[params setValue:self.txtPass2.text forKey:#"pass"];
NSData *body=[NSKeyedArchiver archivedDataWithRootObject:params];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://web.info/ministore/store-commerce/user/register"]];
[request setHTTPBody:body];
[request setHTTPMethod:#"POST"];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue currentQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
if (connectionError){
NSLog(#"Error: %#", connectionError);
[ProgressHUD dismiss];
}
else {
NSLog(#"data as String: %#", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options:NSJSONReadingMutableContainers error:&e];
NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSMutableDictionary *dict1=[dict objectForKey:#"data"];
NSLog(#"data -- %#",[dict objectForKey:#"data"]);
NSLog(#"status -- %#",[dict objectForKey:#"status"]);
int num=[[dict valueForKey:#"status"]intValue];
if( num== 0)
{
NSString *strMail=[dict1 valueForKey:#"mail"];
NSString *strName=[dict1 valueForKey:#"name"];
NSString *strPass=[dict1 valueForKey:#"pass"];
if(strMail.length==0)
{
strMail=#"";
}
if(strName.length==0)
{
strName=#"";
}
if(strPass.length==0)
{
strPass=#"";
}
NSString *Message=[NSString stringWithFormat:#"Please correct the follwing \n %# \n %#\n %# ",strMail,strName,strPass];
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Error" message:Message delegate:nil cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alert show];
}
else
{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:nil message:[NSString stringWithFormat:#"%#",[dict1 objectForKey:#"message"]] delegate:nil cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alert show];
}
if (!jsonArray) {
NSLog(#"Error parsing JSON: %#", e);
}
[ProgressHUD dismiss];
}
}];
The body you posted generated by NSData *body=[NSKeyedArchiver archivedDataWithRootObject:params]; is NSPropertyListBinaryFormat_v1_0 which is a binary serialize data.
Http server could not recognise it. You can POST by JSON
NSData *body = [NSJSONSerialization dataWithJSONObject:"NSDictionary variable name"
options:NSJSONWritingPrettyPrinted
error:&error];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://web.info/ministore/store-commerce/user/register"]];
[request setHTTPBody:body];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-type"];
[request setValue:[NSString stringWithFormat:#"%d", [body length]] forHTTPHeaderField:#"Content-Length"];

Upload image to the PHP server from iOS

I know this question has been asked earlier as well but my issue is a bit different.
I want to upload an image to the PHP server and i want to send more parameters along with an image from an iOS.
I searched on the google and found two solutions:
Either we will send an image as Base64 encoded string in JSON. Referred link.
Or we will upload an image to server using form data. I have referred this link. If someone refers me this way, then please help me to add more parameters in this API.
Now my question is, which one is the best way to upload an image to the server and i have to send more parameters (username, password and more details) in the same web service call.
Thanks in advance.
You can upload image from iOS App to PHP server like this two way:
Using New AFNetworking :
#import "AFHTTPRequestOperation.h"
#import "AFHTTPRequestOperationManager.h"
NSString *stringUrl =#"http://www.myserverurl.com/file/uloaddetails.php?"
NSString *string =#"http://myimageurkstrn.com/img/myimage.png"
NSURL *filePath = [NSURL fileURLWithPath:string];
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:userid,#"id",String_FullName,#"fname",String_Email,#"emailid",String_City,#"city",String_Country,#"country",String_City,#"state",String_TextView,#"bio", nil];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:stringUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
[formData appendPartWithFileURL:filePath name:#"userfile" error:nil];//here userfile is a paramiter for your image
}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"%#",[responseObject valueForKey:#"Root"]);
Alert_Success_fail = [[UIAlertView alloc] initWithTitle:#"myappname" message:string delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[Alert_Success_fail show];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
Alert_Success_fail = [[UIAlertView alloc] initWithTitle:#"myappname" message:[error localizedDescription] delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[Alert_Success_fail show];
}];
Second use NSURLConnection:
-(void)uploadImage
{
NSData *imageData = UIImagePNGRepresentation(yourImage);
NSString *urlString = [ NSString stringWithFormat:#"http://yourUploadImageURl.php?intid=%#",1];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = [NSString stringWithString:#"---------------------------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 stringWithString:[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#\"\r\n", 1]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"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];
[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}
This both way working fine for uploading image from app to php server hope this helps for you.
Using AFNetworking this is how I do it:
NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
[params setObject:#"myUserName" forKey:#"username"];
[params setObject:#"1234" forKey:#"password"];
[[AFHTTPRequestOperationLogger sharedLogger] startLogging];
NSData *imageData;
NSString *urlStr = [NSString stringWithFormat:#"http://www.url.com"];
NSURL *url = [NSURL URLWithString:urlStr];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
imageData = UIImageJPEGRepresentation(mediaFile, 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:nil parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData>formData)
{
[formData appendPartWithFileData:imageData name:#"mediaFile" fileName:#"picture.png" mimeType:#"image/png"];
}];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"File was uploaded" message:#""
delegate:self cancelButtonTitle:#"Close" otherButtonTitles: nil];
[alert show];
}
failure:^(NSURLRequest *request , NSURLResponse *response , NSError *error , id JSON)
{
NSLog(#"request: %#",request);
NSLog(#"Failed: %#",[error localizedDescription]);
}];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite)
{
NSLog(#"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[httpClient enqueueHTTPRequestOperation:operation];
Try with Restkit
Here is link Restkit image upload with parameter
You can get Restkit help from here Restkit integration step
Try this.
-(void)EchoesPagePhotosUpload
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
[self startIndicator];
});
//NSLog(#"%#",uploadPhotosArray);
NSMutableArray *uploadPhotosByteArray=[[NSMutableArray alloc] init];
conversionImage= [UIImage imageWithContentsOfFile:[uploadPhotosArray objectAtIndex:0]];
NSLog(#"conversionImage.size.height %f",conversionImage.size.height);
NSLog(#"conversionImage.size.width %f",conversionImage.size.width);
if(conversionImage.size.height>=250&&conversionImage.size.width>=250)
{
dispatch_async(dispatch_get_main_queue(), ^(void) {
[self performSelectorInBackground: #selector(LoadForLoop) withObject: nil]; NSLog(#"conversionImage.size.height %f",conversionImage.size.height);
NSLog(#"conversionImage.size.width %f",conversionImage.size.width);
for(int img_pos=0;img_pos<[uploadPhotosArray count];img_pos++)
{
conversionImage= [UIImage imageWithContentsOfFile:[uploadPhotosArray objectAtIndex:img_pos]];
NSData *imageData = UIImageJPEGRepresentation(conversionImage,1.0);
[Base64 initialize];
NSString *uploadPhotoEncodedString = [Base64 encode:imageData];
//NSLog(#"Byte Array %d : %#",img_pos,uploadPhotoEncodedString);
[uploadPhotosByteArray addObject:uploadPhotoEncodedString];
}
dispatch_async(dispatch_get_main_queue(), ^{
NSString *photo_description=[webview stringByEvaluatingJavaScriptFromString: #"document.getElementById('UploadPicsDesc').value"];
NSString *uploadPhotoImageName=#"uploadPhoto.jpg";
NSDictionary *UploadpicsJsonResponseDic=[WebserviceViewcontroller EchoesUploadPhotos:profileUserId imageName:uploadPhotoImageName Image:uploadPhotosByteArray PhotoDescription:photo_description];
//NSLog(#"%#",UploadpicsJsonResponseDic);
NSString *UploadPhotosStatusString=[UploadpicsJsonResponseDic valueForKey:#"Status"];
NSLog(#"UploadPhotosStatusString :%#",UploadPhotosStatusString);
NSString *uploadPhotosCallbackstring=[NSString stringWithFormat:#"RefreshForm()"];
[webview stringByEvaluatingJavaScriptFromString:uploadPhotosCallbackstring];
});
});
}
else {
UIAlertView *ErrorAlert=[[UIAlertView alloc] initWithTitle:#"Error" message:#"Please Upload Photo Above 250x250 size" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[ErrorAlert show];
NSLog(#"conversionImage.size.height %f",conversionImage.size.height);
NSLog(#"conversionImage.size.width %f",conversionImage.size.width);
}
}
-(void)uploadImage
{
NSString *mimetype = #"image/jpeg";
NSString *myimgname = _txt_fname.text; //#"img"; //upload image with this name in server PHP FILE MANAGER
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *imageDataa = UIImagePNGRepresentation(chooseImg.image);
NSDictionary *parameters =#{#"fileimg":defaults }; //#{#"uid": [uidstr valueForKey:#"id"]};
AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
//here post url and imagedataa is data conversion of image and fileimg is the upload image with that name in the php code
NSMutableURLRequest *request =
[serializer multipartFormRequestWithMethod:#"POST" URLString:#"http://posturl/newimageupload.php"
parameters:parameters
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageDataa
name:#"fileimg"
fileName:myimgname
mimeType:mimetype];
}];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//manager.responseSerializer = [AFHTTPResponseSerializer serializer];
AFHTTPRequestOperation *operation =
[manager HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success %#", responseObject);
[uploadImgBtn setTitle:#"Uploaded" forState:UIControlStateNormal];
[chooseImg setImage:[UIImage imageNamed:#"invoice-icon.png"]];
if([[responseObject objectForKey:#"status"] rangeOfString:#"Success"].location != NSNotFound)
{
[self alertMsg:#"Alert" :#"Upload sucess"];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure %#", error.description);
[chooseImg setImage:[UIImage imageNamed:#"invoice-icon.png"]];
uploadImgBtn.enabled = YES;
}];
// 4. Set the progress block of the operation.
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {
float myprog = (float)totalBytesWritten/totalBytesExpectedToWrite*100;
NSLog(#"Wrote %f ", myprog);
}];
// 5. Begin!
[operation start];
}
Try this this is work for me.
NSData *postData = [Imagedata dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:apiString]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding: NSUTF8StringEncoding];
NSError *jsonError;
NSData *objectData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *responseDictft = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];

Resources