ios - 第二次运行时,Google map 在 iOS 中显示白屏?

标签 ios iphone xcode google-maps

我正在使用适用于 iOS 的 Google Maps SDK 显示谷歌地图。当我第一次启动 View Controller 时,它可以很好地显示 map 。但是当我第二次转到 View Controller 时,它不显示谷歌地图。它显示空白屏幕。实际上,我正在从那里传递 google geo 编码 api 中的地址,我得到了 lang & lat,然后我显示了 google map 。

显示谷歌地图的代码

//
//  GmapViewController.m
//  MyDex
//  Created by Admin on 8/18/15.
//  Copyright (c) 2015 com.vastedge. All rights reserved.
#import "GmapViewController.h"
#import "AFNetworking.h"
#import "UIKit+AFNetworking.h"
@import GoogleMaps;
@interface GmapViewController ()

@end

@implementation GmapViewController
{
    GMSMapView *mapView_;
    NSString *lat;
    NSString *lng;
    CLLocationDegrees latitude;
    CLLocationDegrees longitude;
    UIActivityIndicatorView *activityView;
}

-(void)geoCodeAddress
{
    NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@":/,."];
    self.address = [[self.address componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];
    NSString *urlString=[NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/geocode/json?address=%@",self.address];

    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:
                 NSUTF8StringEncoding];
    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:urlString]];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    AFHTTPRequestOperation *operation = [manager GET:urlString parameters:nil
                                             success:^(AFHTTPRequestOperation *operation, id responseObject)
                        {
                          NSArray * results = [responseObject objectForKey:@"results"];
                          NSDictionary *records=[results objectAtIndex:0];
                          NSDictionary *geometry=[records objectForKey:@"geometry"];
                          NSLog(@"geomatry is %@",geometry);
                          NSDictionary *latLong=[geometry objectForKey:@"location"];
                          lat=[latLong objectForKey:@"lat"];
                          lng=[latLong objectForKey:@"lng"];
                          latitude=[lat floatValue];
                          longitude=[lng floatValue];
                           NSLog(@"main lat is %f",latitude);
                           NSLog(@"main lng is %f",longitude);
                          [self activityIndicator:@"hide"];
                          [self Loadgmap];
                        }
            failure:^(AFHTTPRequestOperation *operation, NSError *error)
                {
                    NSLog(@"failure string is");
                     [self activityIndicator:@"hide"];
                    UIAlertView *alert =[[UIAlertView alloc]initWithTitle:@"Warning" message:@"Unable to display map" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
                    [alert show];
                }];
    [operation start];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self activityIndicator:@"show"];
    [self geoCodeAddress];
}
-(void)Loadgmap
{
    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.868
                                                            longitude:151.2086
                                                                 zoom:6];
    GMSMapView *mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
    GMSMarker *marker = [[GMSMarker alloc] init];
    marker.position = camera.target;
    marker.snippet = @"Hello World";
    marker.appearAnimation = kGMSMarkerAnimationPop;
    marker.map = mapView;

    self.view = mapView;
}

-(void)activityIndicator:(NSString *)show
{
        if([show isEqual:@"show"])
        {
            NSLog(@"loading shown");

            [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
            activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
            activityView.layer.backgroundColor = [[UIColor colorWithWhite:0.0f alpha:0.5f] CGColor];
            activityView.hidesWhenStopped = YES;
            activityView.frame = self.view.bounds;
            [self.view addSubview:activityView];
            [activityView startAnimating];
        }
        else
        {
            [[UIApplication sharedApplication] endIgnoringInteractionEvents];
            [activityView stopAnimating];
            [activityView removeFromSuperview];
        }
    }

  - (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

最佳答案

使用 dispatch_async(dispatch_get_main_queue(), ^{})是一个更好的做法,但你的主要问题white screen问题是 view在你的ViewController两次被赋予新的值(value)。

[self Loadgmap]在你里面叫viewDidLoad() , self.view = mapView;叫做。当您需要的网络完成后,您的 [self Loadgmap]再次调用,self.view = mapView;再次调用,这会使您的 View 变成白屏。

您应该只为您的 view 赋值在viewDidLoad()方法,而不是稍后在其他方法调用中。

要解决您的问题,您可以进行新的方法调用 -(void)updateMap() :

-(void)updateMap {
    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:[lat floatValue]
                                                            longitude:[lng floatValue]
                                                                 zoom:6];

    GMSMarker *marker = [[GMSMarker alloc] init];
    marker.position = camera.target;
    marker.snippet = @"Hello World";
    marker.appearAnimation = kGMSMarkerAnimationPop;
    marker.map = (GMSMapView*)self.view;

    [((GMSMapView*)self.view) animateToCameraPosition:camera];
}

您应该在网络请求成功 block 中调用它:

 NSArray * results = [responseObject objectForKey:@"results"];
 NSDictionary *records=[results objectAtIndex:0];
 NSDictionary *geometry=[records objectForKey:@"geometry"];
 NSLog(@"geomatry is %@",geometry);
 NSDictionary *latLong=[geometry objectForKey:@"location"];
 lat=[latLong objectForKey:@"lat"];
 lng=[latLong objectForKey:@"lng"];
 latitude=[lat floatValue];
 longitude=[lng floatValue];
 NSLog(@"main lat is %f",latitude);
 NSLog(@"main lng is %f",longitude);
 dispatch_async(dispatch_get_main_queue(), ^{
     [self activityIndicator:@"hide"];
     [self updateMap];
 });

你的 viewDidLoad()应该调用[self Loadgmap]首先将 Google map 初始化为您的 view .

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self activityIndicator:@"show"];
    [self Loadgmap];
    [self geoCodeAddress];
}

完整代码片段:https://gist.github.com/ziyang0621/f66dd536382b1b16597d

enter image description here

关于ios - 第二次运行时,Google map 在 iOS 中显示白屏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32072058/

相关文章:

iphone - 根据用户输入更改UiPickerView值

iphone - iOS - 将 UILabel 从界面生成器连接到代码

ios - 在主界面添加新的 xib 时出错

iphone - 当特定的 nsdate 已过时触发方法

ios - 如何在完成 block 之前解决嵌套的异步调用

ios - AVPlayerViewController 视频的音频后台播放并支持多种格式

ios - 以编程方式在 iphone 处于锁定模式时打开相机应用程序

ios - UIPrintInteractionController 打印到多台 AirPrint 打印机

ios - 本地化 Storyboard

ios - Parse.com - 托管私有(private)文件并有条件地允许下载