I am trying to access a url which is returning some data which has Chinese characters. It returns following response in browser:
{"news":"新聞發佈"}
But when I am trying to read it in my Objective C code I am getting nil in nsdata. Following is my Objective C code:
NSString *final_url = [NSString stringWithFormat:#"http://xx.xxx.xx.xx:xxxx/iph1/NewsAction.do?service=NEWSNOTIF&lang=2&uid=xxxxxxx"];
final_url = [final_url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:final_url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
NSURLResponse *response;
NSError *error = [[NSError alloc] init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *strResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *objectData = [strResponse dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&error];
NSLog(#"json %#",json);
Edit
For testing server guy is sending following data:
String testJson ="新聞發佈";
I there is no error. And data is nil. Then the response form the server itself is not being received. First try by asking the server to send normal string. I think the reason data is nil is not to do with the string encoding here. I suspect the response itself isn't received.
Related
sometimes I get error "index 1 beyond bounds for empty array" at this line
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
This is my full code
+ (NSDictionary *)getJson: (NSString *)strURL parameters:(NSDictionary *)parameters{
NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:15.0];
NSDictionary *headers = #{ #"content-type": #"application/json",
#"cache-control": #"no-cache",
#"postman-token": #"374a4b6f-b660-78f2-78bf-e22cf0156d8d"};
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];*
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:aData options: NSJSONReadingMutableContainers error:&error];
return json;
}
Sometimes I get error, Sometimes not. I don't understands ? please help me, thanks everyone.
Whenever you get an error like the above, try the following:
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:aData options: NSJSONReadingMutableContainers error:&error];
if (error)
{
//1. See what the error says
NSLog(error.localizedDescription);
//2. Convert the original data into a string
NSString *jsonString = [[NSString alloc] initWithData:aData encoding: NSUTF8StringEncoding];
//Now take this string and validate it as a JSON at a place like http://jsonlint.com/
}
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: url
cachePolicy: defaultCachePolicy
timeoutInterval: defaultTimeoutInSeconds];
plz change your cachePolicy with defaultCachePolicy and try :)
Now I m trying to find the tower location using cellID, MNC,MCC and LAC.
If you have the cellId, MNC,MCC and LAC then you can easily find the cell tower location in iOS. after some struggle i get the ans of this problem.
now this is the ans of this question.
#define google_geo_location #"https://www.googleapis.com/geolocation/v1/geolocate?key="
google API LOCATION
NSString * urlString = [NSString stringWithFormat:#"google API key ",google_geo_location];
Create JSON STRING
NSString *json=[NSString stringWithFormat:#"[{\"homeMobileCountryCode\": \"%#\",\"homeMobileNetworkCode\": \"%#\",\"cellTowers\": [{\"cellId\": \"%#\",\"locationAreaCode\": \"%#\",\"mobileCountryCode\": \"%#\",\"mobileNetworkCode\": \"%#\" }]}]",_mcctext,_mnctext,_cellidtext,_lactext,_mcctext,_mnctext];
convert JSON STRING in to JSON DICTIONARY
NSError *jsonError;
NSData *objectData = [json dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsondic = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&jsonError];
Create url from string
NSURL *urlStr=[NSURL URLWithString:urlString];
if (urlStr == nil)
{urlStr = [[NSURL alloc] initWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
}
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:urlStr];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
set request body, If method type is "POST" use only POST
NSData *data=[NSJSONSerialization dataWithJSONObject:jsondic options:NSUTF8StringEncoding error:nil];
NSString* jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"jsonString.....%#",jsonString);
NSData *requestBody = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
// for set requestBody
[request setHTTPBody:requestBody];
now you get response from server
NSHTTPURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSMutableDictionary *resultantDict;
if (responseData != nil)
{
resultantDict=[NSJSONSerialization
JSONObjectWithData:responseData
options:NSJSONReadingMutableLeaves
error:nil];
NSLog(#"resultantDict=%#",resultantDict);
NSString *errorCode=#"";
NSString *errorMessage=#"";
if ([[resultantDict allKeys] containsObject:#"error"])
{
errorCode=[NSString stringWithFormat:#"%#", [[resultantDict valueForKey:#"error"]valueForKey:#"code"]];
errorMessage= [[resultantDict valueForKey:#"error"]valueForKey:#"message"];
}
}
Currently i am using .net Api's for getting response
Here is my iOS source code:
-(void)getUserNameFromFacebbok: (NSString*)newUserName withFacebookId: (NSString*)newFbId withFacebookLoginEmailId: (NSString*)newEmailId withProfilePicUrl: (NSString*)newProfilePicUrl{
NSString * fbApiURLStr =[NSString stringWithFormat:#"http://example.com/api/v1/FacebookUserLogin?UserName=%#&id=%#&emailid=%#&facebookurl=%#",
newUserName,
newFbId,
newEmailId,
newProfilePicUrl];
NSMutableURLRequest *dataRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:fbApiURLStr]];
NSHTTPURLResponse *response =[[NSHTTPURLResponse alloc] init];
NSError* error;
NSData *responseData = [NSURLConnection sendSynchronousRequest:dataRequest returningResponse:&response error:&error];
facebookLoginResponseDict = [NSJSONSerialization JSONObjectWithData:responseData
options:0
error:&error];
}
I am not getting any response dataRequest parameter ====> currently i am getting { URL: (null) }
Can you please help me out how can i solve this issue
Sorry, I found the proper solution like
NSURL *url = [NSURL URLWithString:#"http://example.com/api/v1/FacebookUserLogin?UserName=Brahmam&id=4654566&emailid=ghjnghjnhgh#gmail.com&facebookurl=https://fbjghjghjghjghmkjhgmhjkmhjmh"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response;
NSError *error;
//send it synchronous
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// check for an error. If there is a network error, you should handle it here.
if(!error)
{
//log response
NSLog(#"Response from server = %#", responseString);
}
I'm trying to do a post from my iOS app. The JSON I'm trying to pass is called finalConvertedJson and when I print it on the log, it looks like a good JSON object.
But when I post it using the code below, the web service receives the code as a hex value and doesn't know how to handle it. When I try the same JSON object and URL in Postman, it works perfectly.
self.finalStringJson = [[NSString alloc] initWithData:self.finalConvertedJson encoding:NSUTF8StringEncoding];
NSLog(#"this this: %#", self.finalStringJson);
NSData* responseData = nil;
NSString *urlString = #"http://10.2.176.100:9000/TestIOS?mobileData";
NSURL *url=[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
responseData = [NSMutableData data] ;
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
NSString *bodydata=[NSString stringWithFormat:#"%#",self.finalConvertedJson];
[request setHTTPMethod:#"POST"];
NSData *req=[NSData dataWithBytes:[bodydata UTF8String] length:[bodydata length]];
[request setHTTPBody:req];
NSURLResponse* response;
NSError* error = nil;
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"the final output is:%#",responseString);
I'm guessing it's some sort of encoding issue in my iOS code.
I'm new to iOS so I may be missing something simple here.
I think the problem is on this line...
NSString *bodydata = [NSString stringWithFormat:#"%#",self.finalConvertedJson];
You are using self.finalConvertedJson but I think you intended to use self.finalStringJson. If so, you could just do this...
NSString *bodydata = self.finalStringJson;
Posted a query previously about JSON parsing not working properly. Did more looking into it with a packet sniffer and also with another client that works properly and found out it's a syntax thing, that I still can't seem to solve.
The code in the bottom makes the HTTP request to have the JSON in it as:
{"key":"value"}
And my server is actually looking for a JSON in the following syntax:
key=%22value%22
I tried to write some code that does this manually, but figured there must be something out of the box for iOS, and I don't want to have faults in the future.
I messed around with it for a while trying to find the right code for the job, but couldn't (you can see some code I tried commented out). Can anyone help me?
+ (NSString*)makePostCall:(NSString*)urlSuffix
keys:(NSArray*)keys
objects:(NSArray*)objects{
NSDictionary *params = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
// NSString *dataString = [self getDataStringFromDictionary:params];
// NSData *jsonData = [dataString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params
options:0
error:&error];
// id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
// NSLog(#"%#", jsonObject);
if (!jsonData) {
// should not happen
NSError *error;
NSLog(#"Got an error parsing the parameters: %#", error);
return nil;
} else {
// NSString *jsonRequest = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// NSLog(#"%#", jsonRequest);
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#", urlPrefix, urlSuffix]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
// NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
// [request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: jsonData];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
// TODO: handle error somehow
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return returnString;
}
}