Show Location string using latitude and longitude - ios

I am using this method to show the string of location using current location latitude and longitude but it is showing differently
NSString *urlString = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=false",location.coordinate.latitude, location.coordinate.longitude];
NSError* error;
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error];
NSData *data = [locationString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *dic = [[json objectForKey:#"results"] objectAtIndex:0];
NSArray* arr = [dic objectForKey:#"address_components"];
//Iterate each result of address components - find locality and country
NSString *cityName;
NSString *countryName;
for (NSDictionary* d in arr)
{
NSArray* typesArr = [d objectForKey:#"types"];
NSString* firstType = [typesArr objectAtIndex:0];
if([firstType isEqualToString:#"locality"])
cityName = [d objectForKey:#"long_name"];
if([firstType isEqualToString:#"country"])
countryName = [d objectForKey:#"long_name"];
}
NSString* locationFinal = [NSString stringWithFormat:#"%#,%#",cityName,countryName];
NSLog(#"Final Location %# ",locationFinal);
but final location is showing this type :-
Final Location नठदिलà¥à¤²à¥,India
Why it is showing this type? Can anyone know about this.

Please supply the language with the API params. If language is not supplied, the geocoder attempts to use the preferred language as specified in the Accept-Language header, or the native language of the domain from which the request is sent.
So please replace the code as with the language parameter as like this.
NSString *urlString = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=false&language=en",location.coordinate.latitude, location.coordinate.longitude];
and try again.

I believe that is an uninitialzed variable which is pointing into random memory.
Try:
NSString *cityName = nil;
NSString *countryName = nil;
Short-circuit your for loop:
for (NSDictionary* d in arr)
{
// Add this after the existing code:
if (cityName && countryName)
break;
}
and check for errors before presenting the results:
if (cityName && countryName) {
NSString* locationFinal = [NSString stringWithFormat:#"%#,%#",cityName,countryName];
NSLog(#"Final Location %# ",locationFinal);
} else {
NSLog(#"Failed to find location");
}
Finally your JSON-processing code does no error-checking at all. That's a mistake.

Related

How to use managed object in Objective C?

I got a string with a particular format which have a Entity Name:#"Entry". I can't modify the string. How to access the string? I can access array objects but not inside. How to use initWithEntityName?
Here is the string
<__NSArrayI 0x7fe093f87160>(
<Entry: 0x600000498c90> (entity: Entry; id: 30506398-1852-433D-B536-DC57F484F754> ; data: {
cumulativeTime = 0000;
latitude = “12.972442”
longitude = "77.580643";
type = enrty;
entryName = Bangalore;
}),
<Entry: 0x600000498c90> (entity: Entry; id: 30506398-1852-433D-B536- DC57F484F754> ; data: {
cumulativeTime = 0000;
latitude = “13.067439”
longitude = "80.237617";
type = enrty;
entryName = Chennai;
})
This is how I got the array.
+(NSArray*) routePlan
{
NSString* jsonString = [NSString stringWithContentsOfURL:[[NSBundle mainBundle] URLForResource:#"Documents/DataJson" withExtension:nil]
encoding:NSUTF8StringEncoding error:nil];
NSArray* array = [jsonString componentsSeparatedByString:#","];
}
Do I need to use predicate?
I need the value of latitude and logtude. I can do "po array[0]", but can't go inside of array[0].
Get the below error if I try to access latitude.
error: Execution was interrupted, reason: Attempted to dereference an invalid ObjC Object or send it an unrecognized selector.
The process has been returned to the state before expression evaluation.
If I do po array[0], I got the below.
<__NSArrayI 0x7fe093f87160>(
<Entry: 0x600000498c90> (entity: Entry; id: 30506398-1852-433D-B536-DC57F484F754> ; data: {
cumulativeTime = 0000;
latitude = “12.972442”
longitude = "77.580643";
type = enrty;
entryName = Bangalore;
})
First of all, your file is not in json format.
Now, when you do this :
NSString* aircraftJSONString = [NSString stringWithContentsOfURL:[[NSBundle mainBundle] URLForResource:#"Documents/AircraftDataJson" withExtension:nil]
encoding:NSUTF8StringEncoding error:nil];
NSArray* aircraftJsonFplWaypoints = [aircraftJSONString componentsSeparatedByString:#","];
You are actually splitting your text at the comma, that's why your aircraftJsonFplWaypoints contains 2 object :
Fist a string with value :
<__NSArrayI 0x7fe093f87160>( (entity: Entry;
id: 30506398-1852-433D-B536-DC57F484F754> ; data: { cumulativeTime =
0000; latitude = “12.972442” longitude = "77.580643"; type = enrty;
entryName = Bangalore; })
then a string with value
(entity: Entry; id: 30506398-1852-433D-B536-
DC57F484F754> ; data: { cumulativeTime = 0000; latitude = “13.067439”
longitude = "80.237617"; type = enrty; entryName = Chennai; })
What you have in aircraftJsonFplWaypoints are strings, not dictionary nor array. This will lead you nowhere.
What you need to do is to use regular expression to get what's in the {} . This should work:
{[^}]*}
So I'll do something like :
NSError * error;
NSString * pattern = #"\\{[^\\}]*\\}";
NSRegularExpression * regex = [[NSRegularExpression alloc] initWithPattern:pattern
options:0
error:&error];
NSArray<NSTextCheckingResult *> * matches = [regex matchesInString:aircraftJSONString options:NSMatchingReportCompletion range:NSMakeRange(0, aircraftJSONString.length)];
for(NSTextCheckingResult * match in matches)
{
NSString * substring = [aircraftJSONString substringWithRange:match.range];
// Remove the bracket
substring = [substring substringWithRange:NSMakeRange(1, substring.length - 2)];
// split around the ";" => get the llat/long
NSArray<NSString *>* parts = [substring componentsSeparatedByString:#";"];
NSString * latLong = parts[1];
/* continue to get the longitude and latitude */
}
}
but I would recommend to use a standard for input, for example instead of copy/paste the po output, you can serialize your objects to json with the NSJSONSerialisation API with would make storing/retrieving much easier.
It seems to be the data you are fetching from bundle file is not a valid JSON, it is something else. If it is the JSON data then the below will be the approach to get that.
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"DataJson" ofType:#"json"];
NSLog(#"%#",filePath);
NSURL *url = [NSURL fileURLWithPath:filePath];
NSData *jsonData = [NSData dataWithContentsOfURL:url];
NSError *error = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:&error];
if (error == nil){
NSLog(#"#### JSON object #### %#",jsonObject);
}else{
NSLog(#"#### JSON parsing error #### %#",error);
}
But as you mentioned you have an Entry as ManagedObject, which means you are trying to fetch the data from core data. So that please confirm me how you are saving and fetching data from coredata. (provide me sample code).
If you feel that you are correct with your approach, then please try to print the Entry object properties.
+(NSArray*) routePlan
{
NSString* jsonString = [NSString stringWithContentsOfURL:[[NSBundle mainBundle] URLForResource:#"Documents/DataJson" withExtension:nil]
encoding:NSUTF8StringEncoding error:nil];
NSArray* array = [jsonString componentsSeparatedByString:#","];
[array enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger index, BOOL * _Nonnull stop)
{
Entry* entry = (Entry*)obj;
NSLog(#"id is :: %#",entry.id);
NSLog(#"id is :: %#",entry.data);
}];
return nil;
}

How to separate NSString with multiple commas?

Am having this nsstring
NSString * countryStr = #"6023117,159,en_US,Seychelles,SC,Seychelles,6023185,95,en_US,Kuwait,KW,Kuwait,6023182,172,en_US,Swaziland,SZ,Swaziland,6023185,157,en_US,Saudi Arabia,SA,Saudi Arabia,6023182,177,en_US,Tanzania,TZ,Tanzania,6023185,179,en_US,Togo,TG,Togo,6023185,87,en_US,Cote d'Ivoire,CI,Cote d'Ivoire";
now i want to display only the countries which are suffixed by "en_US".
can anybody tell me how to split that string to get the countries.
I did like this
NSError * error;
NSString* imageName = [[NSBundle mainBundle] pathForResource:#"CountryList" ofType:#"txt"];
NSString * countrStr = [NSString stringWithContentsOfFile:imageName encoding:NSStringEncodingConversionAllowLossy error:&error];
NSArray * dfd = [countrStr componentsSeparatedByString:#"en_US"];
for(int i=0;i<dfd.count;i++)
{
NSString * nama = [dfd objectAtIndex:1];
NSArray * djk = [nama componentsSeparatedByString:#","];
NSString * aksjd = [djk objectAtIndex:1];
}
You can do it like this;
NSString * countryStr = #"6023117,159,en_US,Seychelles,SC,Seychelles,6023185,95,en_US,Kuwait,KW,Kuwait,6023182,172,en_US,Swaziland,SZ,Swaziland,6023185,157,en_US,Saudi Arabia,SA,Saudi Arabia,6023182,177,en_US,Tanzania,TZ,Tanzania,6023185,179,en_US,Togo,TG,Togo,6023185,87,en_US,Cote d'Ivoire,CI,Cote d'Ivoire";
NSArray * arrData = [countryStr componentsSeparatedByString:#","];;//[countryStr componentsSeparatedByString:#"en_US"];
for(int i=0;i<arrData.count;i++)
{
NSString * str = [arrData objectAtIndex:i];
if ([str isEqualToString:#"en_US"] && i<arrData.count-1)
{
NSString* countryName = [arrData objectAtIndex:i+1];
NSLog(#"countryName %#", countryName);
}
}
But you should manage data in your file, loading from resource.
Best way to do it is
NSString *string = [NSString stringWithFormat: #"%#, %#, %#", var1, var2, var3];
Excuse the formatting/syntax errors. Typing this via iPhone. But if there is any errors, look up stringWithFormat: in iOS documents on the apple developer page for corrections.
Your string seems to have the following pattern:
A number,
An other number,
The country language code,
The name,
A short code,
An (other) name.
So what you can do is to use a loop like this:
for (int i = 0; i < dfd.count; i += 6) {
if ( dfd[i + 2] ) } // check the country code at index i + 2
// Do something
}
}

Fetching data from SQLite and want to get only the last value of column id

I am fetching data from SQLite and want to get only the last value of column id in XCode.The code is
NSString *selquery = #"select id from watchlists";
if (self.uid != nil) {
self.uid = nil;
}
self.uid = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:selquery]];
NSString *valvar;
valvar = [_uid lastObject];
NSNumber *custval = [_uid valueForKey: #"#lastObject"];
NSString *imgval1 = [NSString stringWithFormat:#"%#_%s",custval,"1"];
NSLog(#"%#", imgval1);
Please tell me how can I get only the value because by using the above code I am getting array with last value of id.
I think this your case, try this it maybe help you
NSArray *temp=[NSArray arrayWithObjects:#"1",#"2",#"3", nil];
NSArray *temp0ne=[[NSArray alloc]initWithArray:temp];
// NSString *tmmp=[temp0ne lastObject];
NSArray *finalStr=[uid lastObject];
NSLog(#"Dictionary is---->%#",[finalStr lastObject]);
Output:
3_1
EDIT
NSArray *temp=[NSArray arrayWithObjects:#"(1)",#"(2)",#"(3)", nil];
NSArray *temp0ne=[[NSArray alloc]initWithArray:temp];
NSString *tmmp=[temp0ne lastObject];
NSString *final=[tmmp stringByReplacingOccurrencesOfString:#"(" withString:#""];
final=[final stringByReplacingOccurrencesOfString:#")" withString:#""];
NSString *imgval1 = [NSString stringWithFormat:#"%#_%s",final,"1"];
NSLog(#"%#", imgval1);
I don't know is this correct way or not try this....otherwise have look this link
I don't fully understand your code structure hehe. Try this:
NSString *selquery = #"select id from watchlists";
if (self.uid != nil) {
self.uid = nil;
}
self.uid = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:selquery]];
NSNumber *custval = [_uid objectAtIndex:[_uid count]-1];
*
NSString *str = [NSString stringWithFormat#"%#",custval];
str = [str stringByReplacingOccurrencesOfString:#"("
withString:#""];
NSString *finalCustval = [NSString stringWithFormat#"%#",str];
finalCustval = [finalCustval stringByReplacingOccurrencesOfString:#")"
withString:#""];
*
NSString *imgval1 = [NSString stringWithFormat:#"%#_%s",finalCustval ,"1"];
NSLog(#"%#", imgval1);
UPDATE
try adding the ones with *.

Get values out of data from NSJSONSerialization

I have some JSON data which is pulled from a URL. The code I have written works fine to download the JSON and parse it, but I cannot seem to access it how I need too, especially where the data is contained as a sub-element of another one.
Here is the JSON format:
{
address = "<null>";
city = "<null>";
country = UK;
"country_code" = GB;
daylight = 1;
for = daily;
items = (
{
asr = "5:22 pm";
"date_for" = "2013-7-1";
dhuhr = "1:01 pm";
fajr = "2:15 am";
isha = "11:47 pm";
maghrib = "9:24 pm";
shurooq = "4:39 am";
}
);
latitude = "50.9994081";
link = "http://muslimsalat.com/UK";
longitude = "0.5039011";
"map_image" = "http://maps.google.com/maps/api/staticmap?center=50.9994081,0.5039011&sensor=false&zoom=13&size=300x300";
"postal_code" = "<null>";
"prayer_method_name" = "Muslim World League";
"qibla_direction" = "119.26";
query = "51.000000,0.500000";
state = "<null>";
timezone = 0;
title = UK;
"today_weather" = {
pressure = 1020;
temperature = 14;
};
}
(These are Islamic prayer times.)
My Objective-C so far is this:
-(CLLocationCoordinate2D) getLocation{
CLLocationManager *locationManager = [[[CLLocationManager alloc] init] autorelease];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];
return coordinate;
}
//class to convert JSON to NSData
- (IBAction)getDataFromJson:(id)sender {
//get the coords:
CLLocationCoordinate2D coordinate = [self getLocation];
NSString *latitude = [NSString stringWithFormat:#"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", coordinate.longitude];
NSLog(#"*dLatitude : %#", latitude);
NSLog(#"*dLongitude : %#",longitude);
//load in the times from the json
NSString *myURLString = [NSString stringWithFormat:#"http://muslimsalat.com/%#,%#/daily/5.json", latitude, longitude];
NSURL *url = [NSURL URLWithString:myURLString];
NSData *jsonData = [NSData dataWithContentsOfURL:url];
if(jsonData != nil)
{
NSError *error = nil;
id result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
NSArray *jsonArray = (NSArray *)result; //convert to an array
if (error == nil)
NSLog(#"%#", result);
NSLog(#"%#", jsonArray);
for (id element in jsonArray) {
NSLog(#"Element: %#", [element description]);
}
}
}
When running this code, the only output I get is a list of element names (address, city, country, so on). items is given, but not its child elements. I understand that this is what I am asking the code for with:
for (id element in jsonArray) {
NSLog(#"Element: %#", [element description]);
}
but I do not know how to move onto the next step.
The only data values which I require are in fact the times themselves (so, items>asr, items>dhuhr, etc).
How can I get these values themselves and then save them as values I can work with?
Thank you!
(...); - is Array
{...}; - is Dictionary
so your "element" is Dictionary
use objectForKey:
example:
for (id element in jsonArray) {
NSLog(#"Element asr: %#", [element objectForKey:#"asr"]); // or element[#"asr"]
}
NSArray *jsonArray = (NSArray *)result; //convert to an array
This doesn't 'convert', it's just you promising the compiler that result is really an NSArray. And in this case it's a lie.
Your code is currently just printing a list of the keys in the dictionary that is returned in the JSON. Try this to get to the list of items (it's an array so you need to deal with there possibly being multiple entries):
NSDictionary *result = [NSJSONSerialization ...
for (NSDictionary *itemDict in result[#"items"]) {
NSLog(#"item: %#", itemDict);
}
Then you can extract the times.
You can extract info by following:
NSError* error = nil;
NSDictionary *userInfo; //your main data
if([NSJSONSerialization class])
userInfo = [NSJSONSerialization JSONObjectWithData:[request responseData] options:kNilOptions error:&error];
//to extract items
NSDictionary *items = [[[userInfo objectForKey:#"items"] JSONValue] objectAtIndex:0];

How to format data for display in a text view

I have a button that shows some part of the URL on a text view, but I would like for this information to be shown in a specific format.
- (IBAction)Accesos:(id)sender {
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"URL"]];
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
NSArray* Response_array = [json objectForKey:#"avenidas"];
for (int i=0; i < Response_array.count; i++){
NSDictionary* item = [Response_array objectAtIndex:i];
NSString* name = [item objectForKey:#"name"];
NSString* state = [item objectForKey:#"state"];
NSString* space = #"\n";
NSString* formattedString = [NSString stringWithFormat:#"%#%#: %#",space, name, state];
txt_webservice_response.text = formattedString; }
}
The information is shown the same as in the URL I would like to display the information like name: state and then the state to be in color depending the type if it is possible.
NSArray* items = [someDictionary objectForKey:#"avenidas"];
NSDictionary* item = [items objectAtIndex:someIndex];
NSString* name = [item objectForKey:#"name"];
NSString* state = [item objectForKey:#"state"];
NSString* formattedString = [NSString stringWithFormat:#"%#:%#", name, state];
(All of this is first-week stuff -- if you don't know it you need to spend more time studying the fundamentals.)
You can create the HTML for the response and show it to webView for coloring

Resources