I want to find out the weather from the current location.
For that I used the code as
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
[self.locationManager stopUpdatingLocation];
self.location = newLocation;
// NSLog(#"lat long = %f,%f",self.location.coordinate.latitude,self.location.coordinate.longitude);
// Geocode coordinate (normally we'd use location.coordinate here instead of coord).
// This will get us something we can query Google's Weather API with
if (boolCurrentlyWorking == NO) {
CLGeocoder* reverseGeocoder = [[CLGeocoder alloc] init];
if(reverseGeocoder)
{
[reverseGeocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark* placemark = [placemarks objectAtIndex:0];
if (placemark) {
//Using blocks, get zip code
NSString *zipCode = [placemark.addressDictionary objectForKey:(NSString*)kABPersonAddressZIPKey];
NSLog(#"placemark : %# zipcode : %#",placemark.addressDictionary,zipCode);
}
}];
}else{
MKReverseGeocoder *geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:self.location.coordinate];
geocoder.delegate = self;
[geocoder start];
}
}
boolCurrentlyWorking = YES;
}
I am not getting zip code here.
Also found out that this method of didupdate location has been deprecated and new method is
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *location = [locations lastObject];
CLLocation *newlocation = location;
NSLog(#"location : %#",location);
CLGeocoder* reverseGeocoder = [[CLGeocoder alloc] init];
if(reverseGeocoder)
{
[reverseGeocoder reverseGeocodeLocation:newlocation completionHandler:^(NSArray *placemarks, NSError *error) {
for(CLPlacemark *placemark in placemarks)
{
NSLog(#"plcaemark desc : %#",[placemark description]);
}
}];
}
}
But it also does not contain zipcode.
I got this description
{
Country = India;
CountryCode = IN;
FormattedAddressLines = (
NH8C,
Gujarat,
India
);
Name = NH8C;
State = Gujarat;
Street = NH8C;
Thoroughfare = NH8C;
}
Is there like it does not provide zipcode information and we have to build it? If yes then how?
First of all We are not getting any zip code or postal code for India.
Also Google API has been stop working.
I used yahoo api to find out weather.
Here is the code that might help someone
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
[self.locationManager stopUpdatingLocation];
self.location = newLocation;
NSString *linkForWoeid = [NSString stringWithFormat:#" http://where.yahooapis.com/geocode?location=%f,%f&flags=J&gflags=R&appid=zHgnBS4m",self.location.coordinate.latitude,self.location.coordinate.longitude];
NSURL *woeidURL = [NSURL URLWithString:linkForWoeid];
NSData *WoeidData = [NSData dataWithContentsOfURL:woeidURL];
if (WoeidData != NULL)
{
NSError *woeiderr = nil;
NSDictionary *aDicWOEIDResp = [NSJSONSerialization JSONObjectWithData:WoeidData options:NSJSONReadingMutableContainers error:&woeiderr];
NSDictionary *aDictWOEID = [[[[aDicWOEIDResp objectForKey:#"ResultSet"]objectForKey:#"Results"]objectAtIndex:0]objectForKey:#"woeid"];
NSString *address=[NSString stringWithFormat:#"http://weather.yahooapis.com/forecastrss?w=%#",aDictWOEID];
ICB_WeatherConditions *icbWeather = [[ICB_WeatherConditions alloc] initWithQuery:address];
}
#import "ICB_WeatherConditions.m"
- (ICB_WeatherConditions *)initWithQuery:(NSString *)query
{
if (self = [super init])
{
NSURL *url = [NSURL URLWithString:query];
CXMLDocument *parser = [[[CXMLDocument alloc] initWithContentsOfURL:url options:0 error:nil] autorelease];
NSDictionary *namespaceMedia = [NSDictionary dictionaryWithObject:#"http://xml.weather.yahoo.com/ns/rss/1.0" forKey:#"yweather"];
NSArray *nodes = [parser nodesForXPath:#"//channel" error:nil];
for (CXMLNode *node in nodes) {
if ([node kind] == CXMLElementKind)
{
CXMLElement *element = (CXMLElement *)node;
for(int i=0;i<[element childCount];i++)
{
NSString *strKey = [[element childAtIndex:i] name];
if([strKey isEqual:#"location"])
{
location = [self stringForXPath:#"#city" ofNode:[element childAtIndex:i] withNameSpace:namespaceMedia];
}
else if([strKey isEqual:#"item"])
{
NSArray *nodeItem = [element nodesForXPath:#"//item" error:nil];
CXMLElement *elementItem = [nodeItem objectAtIndex:0];
for(int j=0;j<[elementItem childCount];j++){
NSString *strKeyItem = [[elementItem childAtIndex:j] name];
if([strKeyItem isEqual:#"condition"]){
condition =[self stringForXPath:#"#text" ofNode:[elementItem childAtIndex:j] withNameSpace:namespaceMedia];
currentTemp = [[self stringForXPath:#"#temp" ofNode:[elementItem childAtIndex:j] withNameSpace:namespaceMedia] intValue];
}
else if([strKeyItem isEqual:#"forecast"])
{
NSString *date = [self stringForXPath:#"#date" ofNode:[elementItem childAtIndex:j] withNameSpace:namespaceMedia];
NSDate *curDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"dd MMM yyyy";
NSString *strCurDate = [dateFormatter stringFromDate:curDate];
if([date isEqual:strCurDate])
{
highTemp = [[self stringForXPath:#"#high" ofNode:[elementItem childAtIndex:j] withNameSpace:namespaceMedia] intValue];
lowTemp = [[self stringForXPath:#"#low" ofNode:[elementItem childAtIndex:j] withNameSpace:namespaceMedia] intValue];
}
}
}
}
else
continue;
}
}
}
}
return self;
}
This is how I get the weather Details.
In my case I only needed Location,Condition,High Temp,Low Temp,Current Temp.
Related
I have problem with the localization API in Core Location Services. I get the promt that request permission to the location services. If I click Allow and goes to Settings I can see that my app don't have permission.
This is my code in my GeoUtility class:
CLGeocoder *reverseGeocoder = [[CLGeocoder alloc] init];
CLLocationManager *lm = [[CLLocationManager alloc] init];
[lm setPurpose:#"Need to verify your region"];
[lm startUpdatingLocation];
It's trigged by a viewController in the viewDidAppear
I also have added location-services under Required Devices Capabilites in my plist file.
Add CoreLocation.framework and MapKit.framework
And
in .h
#import <MapKit/MapKit.h>
CLLocationManager *locationManager;
CLGeocoder *geocoder;
in view did load
- (void)viewDidLoad
{
locationManager = [[CLLocationManager alloc] init];
geocoder = [[CLGeocoder alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
then
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
LongitudeLbl.text = [NSString stringWithFormat:#"%.8f",currentLocation.coordinate.longitude];
LatitudeLbl.text = [NSString stringWithFormat:#"%.8f",currentLocation.coordinate.latitude];
}
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks lastObject];
NSString *addresstemp2 = [[NSString alloc] init];
NSString *subThoroughfare2 = [NSString stringWithFormat:#"%#",placemark.subThoroughfare];
NSString *thoroughfare2 = [NSString stringWithFormat:#"%#",placemark.thoroughfare];
NSString *postalCode2 = [NSString stringWithFormat:#"%#",placemark.postalCode];
NSString *locality2 = [NSString stringWithFormat:#"%#",placemark.locality];
NSString *administrativeArea2 = [NSString stringWithFormat:#"%#",placemark.administrativeArea];
NSString *country2 = [NSString stringWithFormat:#"%#",placemark.country];
if (![subThoroughfare2 isEqualToString:#"(null)"]) {
addresstemp2 = [NSString stringWithFormat:#"%#",subThoroughfare2];
}
if (![thoroughfare2 isEqualToString:#"(null)"]) {
addresstemp2 = [NSString stringWithFormat:#"%# %# \n",addresstemp2,thoroughfare2];
}
if (![postalCode2 isEqualToString:#"(null)"]) {
addresstemp2 = [NSString stringWithFormat:#"%# %#",addresstemp2,postalCode2];
}
if (![locality2 isEqualToString:#"(null)"]) {
addresstemp2 = [NSString stringWithFormat:#"%# %# \n",addresstemp2,locality2];
}
if (![administrativeArea2 isEqualToString:#"(null)"]) {
addresstemp2 = [NSString stringWithFormat:#"%# %# \n",addresstemp2,administrativeArea2];
}
if (![country2 isEqualToString:#"(null)"]) {
addresstemp2 = [NSString stringWithFormat:#"%# %#",addresstemp2,country2];
}
AddressLbl.text = [[NSString alloc] initWithString:addresstemp2];
[AddressLbl sizeToFit];
[locationManager stopUpdatingLocation];
} else {
}
} ];
}
And you also change setting in your Simulator GO TO THE setting and choose Location Service change it to ON. see down is your application name if it is off then change to ON
I have tried this codes for getting the geolocation based values but not able to get the city name. How do I get the city name?
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
double lati = newLocation.coordinate.latitude;
_geo_coder_latitude_lbl.text= [[NSString stringWithFormat:#"%f",lati] retain];
_geocoder_latitude_str=_geo_coder_latitude_lbl.text;
NSLog(#"print lat;%#",_geocoder_latitude_str);
double longi = newLocation.coordinate.longitude;
_geocoder_longitude_lbl.text= [[NSString stringWithFormat:#"%f",longi] retain];
_geocoder_longitude_str=_geocoder_longitude_lbl.text;
NSLog(#"print lat;%#",_geocoder_longitude_str);
[self._geocoder reverseGeocodeLocation: locationManager.location completionHandler:
^(NSArray *placemarks, NSError *error)
{
//Get address
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(#"Placemark array: %#",placemark.addressDictionary );
//String to address
_located_address = [[placemark.addressDictionary valueForKey:#"FormattedAddressLines"] componentsJoinedByString:#", "];
//Print the location in the console
NSLog(#"Currently address is: %#",_located_address);
// _ex_map_address_lbl.text=_located_address;
}];
[self _storeList_json_parser];
}
See the CLPlacemark docs, [CLPlacemark locatity] will return the city name associated with the placemark.
Check this sample code:
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
double lati = 45.46433;
double longi = 9.18839;
CLLocation *location = [[CLLocation alloc] initWithCoordinate:CLLocationCoordinate2DMake(lati, longi)
altitude:0
horizontalAccuracy:0
verticalAccuracy:0
timestamp:[NSDate date]];
[geocoder reverseGeocodeLocation:location completionHandler:
^(NSArray *placemarks, NSError *error)
{
CLPlacemark *placemark = [placemarks lastObject];
if (error || !placemark)
return;
NSString *city = placemark.locality;
if (!city)
city = placemark.subAdministrativeArea;
NSLog(#"City for location: %#", city);
}];
Currently i am working in iPhone application, Using CLLocationManager to get Latitude and Longitude values fine.
I didn't know this? How to get the device location (Address) name from this latitude and longitude value? please help me
Thanks in Advance
I tried this:
- (void)viewDidLoad
{
[super viewDidLoad];
LocationManager = [[CLLocationManager alloc]init];
LocationManager.delegate=self;
LocationManager.desiredAccuracy = kCLLocationAccuracyBest;
[LocationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSString * latitude = [[[NSString alloc] initWithFormat:#"%f", newLocation.coordinate.latitude]autorelease];
NSString * longitude = [[[NSString alloc] initWithFormat:#"%f", newLocation.coordinate.longitude]autorelease];
[LocationManager stopUpdatingLocation];
NSLog(#"latitude:%#",latitude);
NSLog(#"longitude:%#",longitude);
}
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
[manager stopUpdatingLocation];
lati = [[NSString alloc] initWithFormat:#"%+.6f", newLocation.coordinate.latitude];
NSLog(#"address:%#",lati);
longi = [[NSString alloc] initWithFormat:#"%+.6f", newLocation.coordinate.longitude];
NSLog(#"address:%#",longi);
[geoCoder reverseGeocodeLocation: newLocation completionHandler: ^(NSArray *placemarks, NSError *error)
{
//Get nearby address
CLPlacemark *placemark = [placemarks objectAtIndex:0];
//String to hold address
NSString *locatedAt = [[placemark.addressDictionary valueForKey:#"FormattedAddressLines"] componentsJoinedByString:#", "];
//Print the location to console
NSLog(#"I am currently at %#",locatedAt);
address = [[NSString alloc]initWithString:locatedAt];
NSLog(#"address:%#",address);
}];
}
CLGeocoder *ceo = [[CLGeocoder alloc]init];
CLLocation *loc = [[CLLocation alloc]initWithLatitude:32.00 longitude:21.322];
[ceo reverseGeocodeLocation: loc completionHandler:
^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(#"placemark %#",placemark);
//String to hold address
NSString *locatedAt = [[placemark.addressDictionary valueForKey:#"FormattedAddressLines"] componentsJoinedByString:#", "];
NSLog(#"addressDictionary %#", placemark.addressDictionary);
NSLog(#"placemark %#",placemark.region);
NSLog(#"placemark %#",placemark.country); // Give Country Name
NSLog(#"placemark %#",placemark.locality); // Extract the city name
NSLog(#"location %#",placemark.name);
NSLog(#"location %#",placemark.ocean);
NSLog(#"location %#",placemark.postalCode);
NSLog(#"location %#",placemark.subLocality);
NSLog(#"location %#",placemark.location);
//Print the location to console
NSLog(#"I am currently at %#",locatedAt);
}];
You have ta make some reverse location. You're lucky : Apple provides a class to do that.
See CLGeocoder (for iOS >= 5.0) or MKReverseGeocoder (for iOS < 5.0)
You can use Google Maps API for this (works on any iOS):
NSString *req = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?latlng=%.5f,%.5f&sensor=false&language=da", location.latitude, location.longitude];
NSString *resultString = [NSString stringWithContentsOfURL:[NSURL URLWithString:req] encoding:NSUTF8StringEncoding error:NULL];
Then you can parse this response to NSDictionary using Any JSON library (SBJSON in this case):
SBJSON *jsonObject = [[SBJSON alloc] init];
NSError *error = nil;
NSDictionary *response = [jsonObject objectWithString:resultString error:&error];
[jsonObject release];
Extracting address:
if (error) {
NSLog(#"Error parsing response string to NSObject: %#",[error localizedDescription]);
}else{
NSString *status = [response valueForKey:#"status"];
if ([status isEqualToString:#"OK"]) {
NSArray *results = [response objectForKey:#"results"];
int count = [results count];
//NSSLog(#"Matches: %i", count);
if (count > 0) {
NSDictionary *result = [results objectAtIndex:0];
NSString *address = [result valueForKey:#"formatted_address"];
}
}
}
You have to create a CLLocation object and pass that on to reverseGeoCoder.
Before iOS 5.0 we have MKReverse Geo-coder class to find this..Now it is deprecated..
We have to use CLGeocoder class in Core Location Framework
I want to get the location name from the coordinate value. Here is code,
- (void)viewWillAppear:(BOOL)animated {
CLLocationCoordinate2D zoomLocation;
zoomLocation.latitude = 39.281516;
zoomLocation.longitude= -76.580806;
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 0.5*METERS_PER_MILE, 0.5*METERS_PER_MILE);
MKCoordinateRegion adjustedRegion = [_mapView regionThatFits:viewRegion];
[_mapView setRegion:adjustedRegion animated:YES];
}
So, From that Latitude and longitude , i want to know that location name.
The Below code shall work in ios5 and above
CLGeocoder *ceo = [[CLGeocoder alloc]init];
CLLocation *loc = [[CLLocation alloc]initWithLatitude:32.00 longitude:21.322]; //insert your coordinates
[ceo reverseGeocodeLocation:loc
completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
if (placemark) {
NSLog(#"placemark %#",placemark);
//String to hold address
NSString *locatedAt = [[placemark.addressDictionary valueForKey:#"FormattedAddressLines"] componentsJoinedByString:#", "];
NSLog(#"addressDictionary %#", placemark.addressDictionary);
NSLog(#"placemark %#",placemark.region);
NSLog(#"placemark %#",placemark.country); // Give Country Name
NSLog(#"placemark %#",placemark.locality); // Extract the city name
NSLog(#"location %#",placemark.name);
NSLog(#"location %#",placemark.ocean);
NSLog(#"location %#",placemark.postalCode);
NSLog(#"location %#",placemark.subLocality);
NSLog(#"location %#",placemark.location);
//Print the location to console
NSLog(#"I am currently at %#",locatedAt);
}
else {
NSLog(#"Could not locate");
}
}
];
-(NSString *)getAddressFromLatLon:(double)pdblLatitude withLongitude:(double)pdblLongitude
{
NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%f,%f&output=csv",pdblLatitude, pdblLongitude];
NSError* error;
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error];
// NSLog(#"%#",locationString);
locationString = [locationString stringByReplacingOccurrencesOfString:#"\"" withString:#""];
return [locationString substringFromIndex:6];
}
Use this method
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation: zoomLocation completionHandler:^(NSArray* placemarks, NSError* error){
}
];
In iOS 5.0 and later, you can use CLGeocoder of Core Location framework, as for iOS lower than 5.0, MKReverseGeocoder of Map Kit Framework. Good luck!
Here is block to get address string from current location
in .h file
typedef void(^addressCompletionBlock)(NSString *);
-(void)getAddressFromLocation:(CLLocation *)location complationBlock:(addressCompletionBlock)completionBlock;
in .m file
#pragma mark - Get Address
-(void)getAddressFromLocation:(CLLocation *)location complationBlock:(addressCompletionBlock)completionBlock
{
//Example URL
//NSString *urlString = #"http://maps.googleapis.com/maps/api/geocode/json?latlng=23.033915,72.524267&sensor=true_or_false";
NSString *urlString = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=true_or_false",location.coordinate.latitude, location.coordinate.longitude];
NSError* error;
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error];
NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:[locationString dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:NULL];
NSString *strFormatedAddress = [[[jsonObject valueForKey:#"results"] objectAtIndex:0] valueForKey:#"formatted_address"];
completionBlock(strFormatedAddress);
}
and to call function
CLLocation* currentLocation = [[CLLocation alloc] initWithLatitude:[SharedObj.current_Lat floatValue] longitude:[SharedObj.current_Long floatValue]];
[self getAddressFromLocation:currentLocation complationBlock:^(NSString * address) {
if(address) {
NSLog(#"Address:: %#",address);
}
}];
I have a mapView that has annotation added through JSON (feed is stored in NSDictionary). Everything works great, but I want to add a feature.
I want the mapView to reload all of the annotations each time the view reappears (every time the tab bar is pressed). T've tried putting the part where the JSON is added to the NSDictionary in viewWillAppear {} .... but it does not work.
My code is below. Thanks in advance!
#import "MapViewController.h"
#import "DisplayMap.h"
#import "JSON/JSON.h"
#implementation MapViewController
#synthesize mapView;
#synthesize selectedType;
#synthesize locationManager;
// JSON from Server Actions
- (NSString *)stringWithUrl:(NSURL *)url {
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Fetch the JSON response
NSData *urlData;
NSURLResponse *response;
NSError *error;
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
// Construct a String around the Data from the response
return [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
}
- (id)objectWithUrl:(NSURL *)url {
SBJsonParser *jsonParser = [SBJsonParser new];
NSString *jsonString = [self stringWithUrl:url];
// Parse the JSON into an Object
return [jsonParser objectWithString:jsonString error:NULL];
}
- (NSDictionary *) downloadFeed {
id response = [self objectWithUrl:[NSURL URLWithString:#"http://www.example.com/JSON"]];
NSDictionary *feed = (NSDictionary *)response;
return feed;
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[locationManager startUpdatingLocation];
mapView.mapType = MKMapTypeStandard;
mapView.zoomEnabled = YES;
mapView.scrollEnabled = YES;
mapView.showsUserLocation = YES;
MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };
region.span.longitudeDelta = 0.005;
region.span.latitudeDelta = 0.005;
[mapView setRegion:region animated:YES];
[mapView setDelegate:self];
// Download JSON Feed
NSDictionary *feed = [self downloadFeed];
NSArray *streams = (NSArray *)[feed valueForKey:#"stream"];
int Info;
for (Info = 0; Info < streams.count; Info++) {
NSDictionary *stream = (NSDictionary *)[streams objectAtIndex:Info];
NSLog(#"Time: %#", [stream valueForKey:#"Time"]);
NSLog(#"Type: %#", [stream valueForKey:#"Type"]);
NSLog(#"Longitude: %#", [stream valueForKey:#"Longitude"]);
NSLog(#"Latitude: %#", [stream valueForKey:#"Latitude"]);
double lat = [[stream valueForKey:#"Latitude"] doubleValue];
double lon = [[stream valueForKey:#"Longitude"] doubleValue];
NSString *ttype = [[NSString alloc] initWithFormat: #"%#", [stream valueForKey:#"Type"]];
selectedType = ttype;
CLLocationCoordinate2D coord = {lat, lon};
DisplayMap *ann = [[DisplayMap alloc] init];
ann.title = [NSString stringWithFormat: #"%#", [stream valueForKey:#"Type"]];
ann.subtitle = [NSString stringWithFormat: #"%#", [stream valueForKey:#"Time"]];
ann.coordinate = coord;
[mapView addAnnotation:ann];
}
}
}
}
-(void)viewWillAppear { }
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
CLLocationCoordinate2D loc = [newLocation coordinate];
[mapView setCenterCoordinate:loc];
}
-(IBAction)refreshMap:(id)sender {
// Download JSON Feed
NSDictionary *feed = [self downloadFeed];
NSArray *streams = (NSArray *)[feed valueForKey:#"stream"];
int Info;
for (Info = 0; Info < streams.count; Info++) {
NSDictionary *stream = (NSDictionary *)[streams objectAtIndex:Info];
NSLog(#"Time: %#", [stream valueForKey:#"Time"]);
NSLog(#"Type: %#", [stream valueForKey:#"Type"]);
NSLog(#"Longitude: %#", [stream valueForKey:#"Longitude"]);
NSLog(#"Latitude: %#", [stream valueForKey:#"Latitude"]);
double lat = [[stream valueForKey:#"Latitude"] doubleValue];
double lon = [[stream valueForKey:#"Longitude"] doubleValue];
NSString *ttype = [[NSString alloc] initWithFormat: #"%#", [stream valueForKey:#"Type"]];
selectedType = ttype;
CLLocationCoordinate2D coord = {lat, lon};
DisplayMap *ann = [[DisplayMap alloc] init];
ann.title = [NSString stringWithFormat: #"%#", [stream valueForKey:#"Type"]];
ann.subtitle = [NSString stringWithFormat: #"%#", [stream valueForKey:#"Time"]];
ann.coordinate = coord;
[mapView addAnnotation:ann];
}
}
-(MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation {
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil; //return nil to use default blue dot view
static NSString *AnnotationViewID = #"annotationViewID";
MKAnnotationView *annotationView = (MKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
if (annotationView == nil) {
annotationView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID] autorelease];
}
annotationView.canShowCallout = YES;
if ([annotationView.annotation.title isEqualToString:#"Selected"]) {
UIImage *pinImage = [UIImage imageNamed:#"icon_selected.png"];
[annotationView setImage:pinImage];
}
annotationView.annotation = annotation;
return annotationView;
}
- (void)dealloc {
[mapView release];
self.adView.delegate = nil;
self.adView = nil;
[super dealloc];
}
#end
From UIViewController.h:
- (void)viewWillAppear:(BOOL)animated;
viewWillAppear is not the same as viewWillAppear:. Perhaps if you override the proper method it might work?
I think more details are needed. If viewWillAppear is not getting called then it is probably something to do with the way you are setting up the views.
These two links should give you some pointers.
How do I have a view controller run updating code when it is brought to the top of the stack of views?
and
What's the proper way to add a view controller to the view hierarchy?