I need to do this GET request:
http://api.testmy.co.il/api/sync?BID=1049&ClientCode=3847&Discount=2.34&Service=0&Items=[{"Name":"Tax","Price":"2.11","Quantity":"1","SerialID":"1","Remarks":"","Toppings":""}]&Payments=[]
In browser I get this response:
{
"Success": true,
"Atava": [],
"Pending": [],
"CallWaiter": false
}
But in iOS its not working.
I try:
NSString *requestedURL=[NSString stringWithFormat:#"http://api.testmy.co.il/api/sync?BID=%i&ClientCode=%i&Discount=2.34&Service=0&Items=[{\"Name\":\"Tax\",\"Price\":\"2.11\",\"Quantity\":\"1\",\"SerialID\":\"1\",\"Remarks\":\"\",\"Toppings\":\"\"}]&Payments=[]",BID,num];
NSURL *url = [NSURL URLWithString:requestedURL];
NSURLResponse *response;
NSData *GETReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSString *theReply = [[NSString alloc] initWithBytes:[GETReply bytes] length:[GETReply length] encoding: NSASCIIStringEncoding];
NSLog(#"Reply: %#", theReply);
OR
NSString *requestedURL = [NSString stringWithFormat:#"http://api.testmy.co.il/api/sync?BID=%i&ClientCode=%i&Discount=2.34&Service=0&Items=[{'Name':'Tax','Price':'2.11','Quantity':'1','SerialID':'1','Remarks':'','Toppings':''}]&Payments=[]", BID, num];
OR
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
[params setObject:#"Tax" forKey:#"Name"];
[params setObject:#"2.11" forKey:#"Price"];
[params setObject:#"1" forKey:#"Quantity"];
[params setObject:#"1" forKey:#"SerialID"];
[params setObject:#"" forKey:#"Remarks"];
[params setObject:#"" forKey:#"Toppings"];
NSData *jsonData = nil;
NSString *jsonString = nil;
if([NSJSONSerialization isValidJSONObject:params])
{
jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:nil];
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"%#", jsonString);
}
NSString *get = [NSString stringWithFormat:#"&Items=%#", jsonString];
NSData *getData = [get dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"GET"];
[request setTimeoutInterval:8];
[request setHTTPBody:getData];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
I tried all above code but it doesn't work(long time out.. just stuck on this).How to fixing this?
This is because your URL is not correct, this string should add percent escape. Try with this:
NSString *requestedURL=[NSString stringWithFormat:#"http://api.testmy.co.il/api/sync?BID=%i&ClientCode=%i&Discount=2.34&Service=0&Items=[{'Name':'Tax','Price':'2.11','Quantity':'1','SerialID':'1','Remarks':'','Toppings':''}]&Payments=[]",BID,num];
NSURL *url = [NSURL URLWithString:[requestedURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//and you use this url
// Send a synchronous request
NSURLRequest * urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:#"enter your url here"]];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
if (error == nil)
{
// Parse data here
}
The NSURLResponse and NSError vars are passed into the sendSynchronousReqeust method so when it returns, they will be populated with the raw response and error (if any). If you need to check for stuff like response codes you can do so via the “response” variable you pass.
Related
I tired picker view with array of four element from url link "branch_name"
(1) with button action.
Button action:
- (IBAction)picker_button:(id)sender {
NSString *parseURL =#"url(1)";
NSString *encodeurl =[parseURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:encodeurl];
NSData *data = [NSData dataWithContentsOfURL:url];
if(data){
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options: kNilOptions error:&error];
arrMsg = [json valueForKeyPath:#"Branches.branch_name"];
NSLog(#"%#",json);
arrmsg1 =[json valueForKeyPath:#"Branches.id"];
[_pickerdata1 reloadAllComponents];
}
}
Then I used url link(2) passing parameter using POST NSURLConnection and successfully displayed in tableview.
Post method coding:
here i am passing parameter as Branchid=#"1" only but i want to pass parameter as entire branchid value. help me
-(void) sendDataToServer : (NSString *) method{
NSString *Branchid =#"1" ;
NSURL *url = nil;
NSMutableURLRequest *request = nil;
if([method isEqualToString:#"GET"]){
NSString *getURL = [NSString stringWithFormat:#"%#?branch_id=%#", URL, Branchid];
url = [NSURL URLWithString: getURL];
request = [NSMutableURLRequest requestWithURL:url];
NSLog(#"%#",getURL);
}else{ // POST
NSString *parameter = [NSString stringWithFormat:#"branch_id=%#",Branchid];
NSData *parameterData = [parameter dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
url = [NSURL URLWithString: URL];
NSLog(#"%#", parameterData);
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPBody:parameterData];
arr= [NSMutableString stringWithUTF8String:[parameterData bytes]];
}
[request setHTTPMethod:method];
[request addValue: #"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if( connection )
{
mutableData = [NSMutableData new];
}
}
connection did finish loading:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError* error;
json = [NSJSONSerialization JSONObjectWithData: mutableData
options:kNilOptions
error:&error];
NSLog(#"%#",json);
sellArray = [json valueForKeyPath:#"BranchByList.sell"];
buyArray = [json valueForKeyPath:#"BranchByList.buy"];
updataedArray = [json valueForKeyPath:#"BranchByList.updated"];
imageArray = [json valueForKeyPath:#"BranchByList.flag_image"];
currency =[json valueForKeyPath:#"BranchByList.currency"];
[ _dataview reloadData];
}
I Have implemented this code. When I run it for the first time, it gives a response. But When I Run it the Second time, it gives error like....
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (No value.) UserInfo=0x178265540 {NSDebugDescription=No value.
But Whenever I uninstalled and rebuild it gives response.
NSMutableArray *data=[[NSMutableArray alloc]initWithObjects:#"type",#"st_eml",#"st_pwd",nil];
NSMutableArray *value=[[NSMutableArray alloc]initWithObjects:#"normal", #"Huhn",#"1234", nil];
//NSArray *keys = [[NSArray alloc ]initWithObjects:#"type", #"st_eml", #"st_pwd", nil];
//NSArray *objects = [[NSArray alloc]initWithObjects:#"normal", #"Huhn",#"123", nil];
NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:value forKeys:data];
// Serialize the data
NSError *error = NULL;
NSData *theJSONData = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary error:&error];
NSLog(#"Serialization Error: %#", error);
// Change the data back to a string
NSString* theStringObject = [[NSString alloc] initWithData:theJSONData encoding:NSUTF8StringEncoding];
// Determine the length of the data
NSData *requestData = [theStringObject dataUsingEncoding:NSUTF8StringEncoding];
NSString* requestDataLengthString = [[NSString alloc] initWithFormat:#"%lu", (unsigned long)[requestData length]];
// Create request to send to web service
NSString *strurl = #"http://testing.singletreffen.de/appapi/v1/login";
NSString* webStringURL = [strurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:webStringURL]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:requestData];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:requestDataLengthString forHTTPHeaderField:#"Content-Length"];
[request setTimeoutInterval:30.0];
// Deserialize the response
NSData *returnData = [ NSURLConnection sendSynchronousRequest: request returningResponse: nil error:&error];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
I have tried your code, made some changes in parsing and it's working properly and giving response also
NSMutableArray *data=[[NSMutableArray alloc]initWithObjects:#"type",#"st_eml",#"st_pwd",nil];
NSMutableArray *value=[[NSMutableArray alloc]initWithObjects:#"normal", #"Huhn",#"1234", nil];
NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:value forKeys:data];
// Serialize the data
NSError *error = nil;
NSData *theJSONData = [NSJSONSerialization dataWithJSONObject:theRequestDictionary options:0 error:&error];
NSLog(#"Serialization Error: %#", error);
// Change the data back to a string
NSString* theStringObject = [[NSString alloc] initWithData:theJSONData encoding:NSUTF8StringEncoding];
// Determine the length of the data
NSData *requestData = [theStringObject dataUsingEncoding:NSUTF8StringEncoding];
NSString* requestDataLengthString = [[NSString alloc] initWithFormat:#"%lu", (unsigned long)[requestData length]];
// Create request to send to web service
NSString *strurl = #"http://testing.singletreffen.de/appapi/v1/login";
NSString* webStringURL = [strurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:webStringURL]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:requestData];
[request setHTTPBody:requestData];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:requestDataLengthString forHTTPHeaderField:#"Content-Length"];
[request setTimeoutInterval:30.0];
// Deserialize the response
NSData *returnData = [ NSURLConnection sendSynchronousRequest: request returningResponse: nil error:&error];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(#"LOG : %#", returnString);
This is my code for sending a post request to a nodejs backend.
CLLocation* location = [locationManager location];
CLLocationCoordinate2D coord = [location coordinate];
NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://50.63.172.74:8080/points"]];
//[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
NSDictionary* jsonDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:coord.latitude], #"lat", [NSNumber numberWithFloat:coord.longitude], #"lng", nil];//dictionaryWithObjectsAndKeys:coord.latitude, nil]
NSString *postString;
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
if (! jsonData) {
NSLog(#"Got an error: %#", error);
} else {
postString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
(void)[[NSURLConnection alloc] initWithRequest:request delegate:self];
Using express I'm getting the request.body back on the server but it looks like this:
{ '{\n "lat" : 0.0,\n "lng" : 0.0\n}': '' }
and I can't access it by just saying request.body.lat since it comes back as undefined.
I want the body to look like:
{ "lat":0.0, "lng":0.0}
Any idea on how to do that using express?
May this help you.
Please replace 0.0 with your actual coordiantes
NSArray *keys = [NSArray arrayWithObjects:#"lat", #"lng", nil];
NSArray *objects = [NSArray arrayWithObjects:#"0.0",#"0.0", nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSData *jsonData ;
NSString *jsonString;
if([NSJSONSerialization isValidJSONObject:jsonDictionary])
{
jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:nil];
jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
}
NSString *requestString = [NSString stringWithFormat:
#"http://50.63.172.74:8080/points"];
NSURL *url = [NSURL URLWithString:requestString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: jsonData];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [jsonData length]] forHTTPHeaderField:#"Content-Length"];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned) {
NSLog(#"Error %#",errorReturned.description);
}
else
{
NSError *jsonParsingError = nil;
NSMutableArray *arrDoctorInfo = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParsingError];
NSLog(#"Dict %#",arrDoctorInfo);
}
The problem is that after you use NSJSONSerialization to obtain a NSData object containing your JSON data, you then create postString from that data. Eliminate that unnecessary step, and just do:
[request setHTTPBody:jsonData];
And you should get the expected JSON in your server-side code.
Someone please help me in this query.
How to Get JSON data From a URL Which contains .SVC file in iphone (ios5)?
The link is like : http://156.160.45.118/api/Login.svc?wsdl (not original)
and parameters are: email and password.
So how can I verify the login credentials?
My code :
NSString *username = emailField.text;
NSString *password = passwordField.text;
NSMutableDictionary *dictionnary = [NSMutableDictionary dictionary];
[dictionnary setObject:username forKey:#"user_email"];
[dictionnary setObject:password forKey:#"user_password"];
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary
options:kNilOptions
error:&error];
NSString *urlString = #"http://156.160.45.118/api/Login.svc?wsdl";
NSURL *url = [NSURL URLWithString:urlString];
// Prepare the request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"json" forHTTPHeaderField:#"Data-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:jsonData];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&theResponse
error:&errorReturned];
if (errorReturned)
{
//...handle the error
}
else
{
NSString *retVal = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(#"%#", retVal);
}
Finally i got my answer By researching lot of things.
NSString *username = emailField.text;
NSString *password = passwordField.text;
NSMutableDictionary *dictionnary = [NSMutableDictionary dictionary];
[dictionnary setObject:username forKey:#"user_email"];
[dictionnary setObject:password forKey:#"user_password"];
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary
options:kNilOptions
error:&error];
NSString *urlString = http://156.160.45.118/api/Login.svc/login;
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] ;
NSLog(#"%#", responseString);
I am trying to build an app with a map in which the user would select his origin address and destination address.. It all works fine, but I can't access the Google API Distance Matrix..
I am try with following:
NSString *urlPath = [NSString stringWithFormat:#"/maps/api/distancematrix/xml?origins=%#=%#&mode=driving&language=en-EN&sensor=false" ,polazisteField.text , odredisteField.text];
NSURL *url = [[NSURL alloc]initWithScheme:#"http" host:#"maps.googleapis.com" path:urlPath];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc]init]autorelease];
[request setURL:url];
[request setHTTPMethod:#"GET"];
NSURLResponse *response ;
NSError *error;
NSData *data;
data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *result = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
address.text = result;
, but have no luck, any idea how to resolve this?
I think your call has been considred as invalid API call.
try below code that is edited from your code snippet.
NSString *urlPath = [NSString stringWithFormat:#"/maps/api/distancematrix/json?origins=%#&destinations=%#&mode=driving&language=en-EN&sensor=false" ,polazisteField.text , odredisteField.text];
NSURL *url = [[NSURL alloc]initWithScheme:#"http" host:#"maps.googleapis.com" path:urlPath];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:url];
[request setHTTPMethod:#"GET"];
NSURLResponse *response ;
NSError *error;
NSData *data;
data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSMutableDictionary *jsonDict= (NSMutableDictionary*)[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSMutableDictionary *newdict=[jsonDict valueForKey:#"rows"];
NSArray *elementsArr=[newdict valueForKey:#"elements"];
NSArray *arr=[elementsArr objectAtIndex:0];
NSDictionary *dict=[arr objectAtIndex:0];
NSMutableDictionary *distanceDict=[dict valueForKey:#"distance"];
NSLog(#"distance:%#",[distanceDict valueForKey:#"text"]);
NSString *result = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
address.text = [distanceDict valueForKey:#"text"];