在 UIView 中重新加载 JSON Feed

发布于 2024-10-09 16:22:38 字数 6093 浏览 0 评论 0原文

我有一个通过 JSON 添加注释的 mapView(提要存储在 NSDictionary 中)。一切都很好,但我想添加一个功能。

我希望 mapView 在每次视图重新出现时(每次按下选项卡栏时)重新加载所有注释。我尝试将 JSON 添加到 NSDictionary 的部分放在 viewWillAppear {} .... 但它不起作用。

我的代码如下。提前致谢!

#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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

烟花易冷人易散 2024-10-16 16:22:38

来自 UIViewController.h:

- (void)viewWillAppear:(BOOL)animated;

viewWillAppearviewWillAppear: 不同。也许如果你重写正确的方法它可能会起作用?

From UIViewController.h:

- (void)viewWillAppear:(BOOL)animated;

viewWillAppear is not the same as viewWillAppear:. Perhaps if you override the proper method it might work?

绝情姑娘 2024-10-16 16:22:38

我认为需要更多细节。如果 viewWillAppear 没有被调用,那么这可能与您设置视图的方式有关。

这两个链接应该会给您一些指导。
当视图控制器被带到视图堆栈的顶部时,如何让它运行更新代码?


正确的添加方法是什么视图层次结构的视图控制器?

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文