How to post data in url using json? - ios

This is my code by which i am posting data in url.
- (IBAction)Register:(id)sender {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://dev1.brainpulse.org/quickmanhelp/webservice/api.php?act=registration"]];
[request setHTTPMethod:#"POST"];
NSLog(#"the company name is:%#",_CompanyName.text);
NSLog(#"the email is:%#",_Email.text);
NSLog(#"the password is:%#",_Password.text);
NSLog(#"the password again is:%#",_Passwordagin.text);
NSString *strParameters =[NSString stringWithFormat:#"email_id=%#&company_name=%#&password=%#",_Email.text,_CompanyName.text,_Password.text, nil];
NSLog(#"the data Details is =%#", strParameters);
NSData *data1 = [strParameters dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data1];
// NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Handle your response here
//}];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
NSLog(#"got response==%#", resSrt);
if(resSrt)
{
NSLog(#"got response");
}
else
{
NSLog(#"faield to connect");
}
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"[http://dev1.brainpulse.org/quickmanhelp/webservice/api.php?act=registration"];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request1 addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request1 addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request1 setHTTPMethod:#"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"company_name", _CompanyName.text,
#"email_id", _Email.text,#"password", _Password.text,
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Handle your response here
}];
[postDataTask resume];

NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"[http://dev1.brainpulse.org/quickmanhelp/webservice/api.php?act=registration"];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request1 addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request1 addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request1 setHTTPMethod:#"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"company_name", _CompanyName.text,
#"email_id", _Email.text,#"password", _Password.text,
nil];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *bodyData = [NSJSONSerialization dataWithJSONObject:mapData options:NSJSONWritingPrettyPrinted error:&error];
[request setHTTPBody:bodyData];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *strResponce = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSMutableDictionary *dictResponse = [NSJSONSerialization JSONObjectWithData:[strResponce dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:&error];
NSLog(#"Result: %#",dictResponse);

Try the code in this gist I created
Which is generated using PAW .

Related

I want to upload image with other parameters to server using objective c

well am new to iOS and i encountered a situation where i have to upload a image to server. Here is what am doing in the post method.
- (IBAction)submitClicked:(UIButton *)sender {
NSDictionary *inputData = [NSDictionary dictionaryWithObjectsAndKeys:myImage,#"coverPic", nil];
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://api.mapartment.in/index.php/events/create"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:70.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSData *jsonInputData = [NSJSONSerialization dataWithJSONObject:inputData options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonInputString = [[NSString alloc] initWithData:jsonInputData encoding:NSUTF8StringEncoding];
[request setHTTPBody:[jsonInputString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
dispatch_async(dispatch_get_main_queue(), ^{
NSDictionary *jsondictcity_name = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
if([[jsondictcity_name valueForKey:#"result"] isEqual:#"true"]){
NSLog(#"Success");
}
else{
NSLog(#"Try Again");
}
[self.view resignFirstResponder];
});
}
];
[postDataTask resume];
}
P.S. _localFilePath contains - /Users/appcode/Library/Developer/CoreSimulator/Devices/3C3567B8-03BC-4233-B0BC-97E3899D0AAA/data/Containers/Data/Application/3D574024-42FB-4305-807A-ACC3C128383F/Documents/png
Image will not pass with other parameter,you have to convert image into NSData
UIImage *yourImage= [UIImage imageNamed:#"image.png"];
NSData *imageData = UIImagePNGRepresentation(yourImage);
NSString *postLength = [NSString stringWithFormat:#"%d", [imageData length]];
and then pass these data in request
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:imageData];
and other parameter pass as json.
to get UIImage from path use
UIImage *yourImage = [UIImage imageWithContentsOfFile: imageFilePath];
- (IBAction)submitClicked:(UIButton *)sender {
UIImage* image = [UIImage imageWithContentsOfFile:_localFilePath];
NSString *myImage = [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
NSDictionary *inputData = [NSDictionary dictionaryWithObjectsAndKeys:myImage,#"coverPic",#"POEM WRITING",#"title",#"Bring your own paper",#"desc", nil];
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://api.mapartment.in/index.php/events/create"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:70.0];
[request addValue:#"multipart/form-data" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSData *jsonInputData = [NSJSONSerialization dataWithJSONObject:inputData options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonInputString = [[NSString alloc] initWithData:jsonInputData encoding:NSUTF8StringEncoding];
[request setHTTPBody:[jsonInputString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
dispatch_async(dispatch_get_main_queue(), ^{
NSDictionary *jsondictcity_name = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
if([[jsondictcity_name valueForKey:#"result"] isEqual:#"true"]){
NSLog(#"Success");
}
else{
NSLog(#"Try Again");
}
[self.view resignFirstResponder];
});
}
];
[postDataTask resume];
}

How to fetch Data from the web services using NSURLSession?

I have made one demo code for print the data from the web Services,
Code
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://54.149.46.64/API/video.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"video" forHTTPHeaderField:#"list"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
}] resume];
Output
JSON_Webservices[4496:150468] requestReply: {"Status":"Fail","Message":"Please enter required fields"}
Why i am not able to fetch data from the WS? Please help me.
Working Fine In Postman
Image
Thank You.
header
Please check this...
NSURL *aUrl = [NSURL URLWithString:#"XXXX"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
NSString *postString = #"list=video";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
NSError *jsonError;
NSData *objectData = [requestReply dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
NSLog(#"requestReply: %#", json);
}] resume];

How to solve warning message: Sending 'viewController const __strong to parameter of incompatible type 'id<nsurlsessiondelegate>

The following code gave a warning of :
Sending 'viewController const __strong to parameter of incompatible
type 'id
Here is my code:
- (void)postRequestWithParam: (NSDictionary *)param onCompletion: (CompletionHandler)completionHandler
{
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.timeoutIntervalForRequest = 30.0;
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString: #"http://test.demo.net/demoapp/index.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
if(param == nil)
param = [NSDictionary dictionary];
NSData *postData = [NSJSONSerialization dataWithJSONObject:param options:0 error:&error];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
if (!error)
{
completionHandler(YES, [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error], nil);
NSString *responseStr = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"res...%#",responseStr);
NSLog(#"RESPONSE: %#", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]);
}
else
{
completionHandler(NO, nil, error);
}
}];
[postDataTask resume];
}
Confirm <NSURLSessionDelegate> in your header file and it will solve the issue i think,
#interface ViewController : UIViewController <NSURLSessionDataDelegate>
It is because you are setting delegate to self in NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil]; So it's requires to confirm NSURLSessionDataDelegate protocol.

how to handle response in json

I'm using this piece of code for hit data in url.
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://dev1.brainpulse.org/quickmanhelp/webservice/api.php?act=registration"];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request1 addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request1 addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request1 setHTTPMethod:#"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"company_name", _CompanyName.text,
#"email_id", _Email.text,#"password", _Password.text,nil];
NSLog(#"Result: %#",request1);
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request1 setHTTPBody:postData];
NSURLResponse *response = nil;
// NSError *error = nil;
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request1 completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Handle your response here
NSLog(#"Result: %#",mapData);
NSLog(#"Result: %#",request1);
NSLog(#"Result: %#",data);
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(#"Result: %#",dictionary);
NSLog(#"Result error : %#",error.description);
}];
[postDataTask resume];
value of uitextfield is not store in url when i clicked on button, what should i do here?
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://dev1.brainpulse.org/quickmanhelp/webservice/api.php?act=registration"];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request1 addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request1 addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request1 setHTTPMethod:#"POST"];
//NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: _CompanyName.text,#"company_name",
//_Email.text,#"email_id", _Password.text,#"password",nil];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"yyyyy",#"company_name",
#"karthik.saral#gmail.com",#"email_id", #"XXXXX",#"password",nil];
NSLog(#"Result: %#",request1);
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request1 setHTTPBody:postData];
NSURLResponse *response = nil;
// NSError *error = nil;
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request1 completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Handle your response here
NSLog(#"Result: %#",mapData);
NSLog(#"Result: %#",request1);
NSLog(#"Result: %#",data);
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(#"Result: %#",dictionary);
NSLog(#"Result error : %#",error.description);
NSLog(#"answewrv : %#",dictionary);
NSLog(#"Result error : %#",error.description);
}];
[postDataTask resume];
this is updated code after the amendments. i am getting the same error.
You are wrong here:
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"company_name", _CompanyName.text,
#"email_id", _Email.text,#"password", _Password.text,nil];
It should be
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: _CompanyName.text,#"company_name",
_Email.text,#"email_id", _Password.text,#"password",nil];
initWithObjectsAndKeys mean: object,key, object, key
I have done also this type work you can see this , may be it will help you.
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#" your URL "];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *mapData = [NSString stringWithFormat:#"username=%#&password=%#&api_key=Your key", usernameField.text,passwordField.text];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSLog(#"%#", mapData);
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"Data = %#",text);
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if(error!=nil)
{
NSLog(#"error = %#",error);
}
dispatch_async(dispatch_get_main_queue(), ^{
[self checkUserSuccessfulLogin:json];
});
}
else{
NSLog(#"Error : %#",error.description);
}
}];
[postDataTask resume];
}
- (void)checkUserSuccessfulLogin:(id)json
{
// NSError *error;
NSDictionary *dictionary = (NSDictionary *)json;
if ([[dictionary allKeys] containsObject:#"login"])
{
if ([[dictionary objectForKey:#"login"] boolValue])
{
[self saveLoginFileToDocDir:dictionary];
ItemManagement *i = [[ItemManagement alloc]init];
[self presentViewController:i animated:YES completion:Nil];
}
else
{
NSLog(#"Unsuccessful, Try again.");
UIAlertView *alertLogin = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Wrong Username Or Password" delegate:self cancelButtonTitle:#"cancel" otherButtonTitles:nil];
[alertLogin show];
}
}
}
- (void)saveLoginFileToDocDir:(NSDictionary *)dictionary
{
NSArray *pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *pListdocumentsDirectory = [pListpaths objectAtIndex:0];
NSString *path = [pListdocumentsDirectory stringByAppendingPathComponent:#"Login.plist"];
BOOL flag = [dictionary writeToFile:path atomically:true];
if (flag)
{
NSLog(#"Saved");
}
else
{
NSLog(#"Not Saved");
}
}

how to pass a dictionary using NSURLSession in post method?

I do not know how to pass values in dictionary into server using NSURLSession via POST. Please help me to solve this problem.
My dictionary contains contact information (name and phone number only), where the key is the person's name and the value is their phone number.
I have sample code using nsurl connection - how can I convert it to use NSURLSession?
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://holla.com/login"]];
request.HTTPMethod = #"POST"; [request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:#"212333333",#"ABCD",#"6544345345",#"NMHG", nil];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
request.HTTPBody = jsonData;
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
I solve the problem by using the following method:
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL * url = [NSURL URLWithString:[ NSString stringWithFormat:#"http://xxxx.com/login/save_contact"]];;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys:#"212333333",#"ABCD",#"6544345345",#"NMHG",
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"Data = %#",text);
}
}];
[postDataTask resume];

Resources