简体   繁体   English

使用Json时currentCenter返回nil iOS

[英]currentCenter returning nil iOS while using Json

The JSON Data JSON数据

Please HELP I beg 请帮助我

  2015-10-30 12:15:58.866 GooglePlaces[17141:989254] Google Data: (
    {
        geometry =         {
            location =             {
                lat = "55.599881";
                lng = "-2.64616";
            };
        };
        icon = "https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png";
        id = 4e3047fc80549f89389827d05fb89a999705fcf2;
        name = "Scott's view";
        photos =         (
                        {
                height = 2368;
                "html_attributions" =                 (
                    "<a href=\"https://maps.google.com/maps/contrib/113818044483598102211\">Clarke Thomas</a>"
                );
                "photo_reference" = "CmRdAAAADgCHDAr9O_RZg24-kHykYexBOTpKfhOAWTV-K1Go-sn6CGUoikhGc3beyjErYvXzCPLwFLRr32lC8tPpgfIA-CXue6l75ziHrlRXMOt72IZFBcbZfCBSSbttW5lHjSdfEhD5d08GC5Myl8L1_Zs0VmW2GhTzCD7bh_klEqsROxGDZLvskhzaBw";
                width = 3200;
            }
        );
        "place_id" = ChIJP5eCRF54h0gR9nc97bjfO8k;
        rating = "4.7";
        reference = "CmRgAAAAfN6yeOvYQEeRAzOcidZiE83kPoIdw_vDDH7orFr3gbZVXHeb3prAMlOCVWnVqeeK786c8x-V1QUtWfpSn-50Bk4Q5lO7fY04cNLsXigf1nx1JWiTee5d4TdKI1ij-jGDEhDXYtJPM_1H5t9KhqdSJiyuGhQAXqV2rosfllEOfE-suQ_ur89Bmg";
        scope = GOOGLE;
        types =         (
            parking,
            "point_of_interest",
            establishment
        );
        vicinity = B6356;
    },
        {
        geometry =         {
            location =             {
                lat = "55.756977";
                lng = "-4.17221";
            };
        };
        icon = "https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png";
        id = 481f927c8ea30c24ae902a14dd85efd7e2bae1d1;
        name = "Kwik Fit";
        "opening_hours" =         {
            "open_now" = 1;
            "weekday_text" =             (
            );
        };
        photos =         (
                        {
                height = 608;
                "html_attributions" =                 (
                    "<a href=\"https://maps.google.com/maps/contrib/118136503820442451002\">Kwik Fit</a>"
                );
                "photo_reference" = "CmRdAAAAY152xIVsahSMoZgsMMN1IdIlMq6fbPeMCJ_1feXg1BIOhRTaW-s_wauDF8WSVPXnOG4dOR3nE9fLzqHmTmdoyKIAef_tZVFKOK43880DeItFOKNejmt_QaEamB4nX8uvEhCPQYbVi8day5vi1KSzGPFtGhT8KzkGs_FuA5ZM11lydRplhPM8uA";
                width = 1080;
            }
        );
        "place_id" = "ChIJ1zdwq2s_iEgR1fI1QvrsCas";
        reference = "CmRcAAAAkkARPnw1ApSjDPECBxsmTmcDDr5LESbSAWF0aNPvI2rX8BDJGfUj3dytKOotK2IbsCUaFbbhYZ8mgoDXfvYqtGliy2v06F2CarEAPSfD_25BGRYqUBsNKYiO05c-seGUEhDsuTEEt6PPKoZhmkBkj2VFGhQ-5vq-S7o73KmF2zw-MIJsPpWYgg";
        scope = GOOGLE;
        types =         (
            store,
            parking,
            "car_repair",
            "point_of_interest",
            establishment
        );
        vicinity = "1 Telford Road, East Kilbride";
    },
        {
        geometry =         {
            location =             {
                lat = "55.618894";
                lng = "-2.810683";
            };
        };
        icon = "https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png";
        id = 8ec3c7e9dc0da1d102d516107178cd440579ecff;
        name = "Kwik-Fit";
        "opening_hours" =         {
            "open_now" = 1;
            "weekday_text" =             (
            );
        };
        photos =         (
                        {
                height = 608;
                "html_attributions" =                 (
                    "<a href=\"https://maps.google.com/maps/contrib/102672183870059691928\">Kwik-Fit</a>"
                );
                "photo_reference" = "CmRdAAAAfbp51L51v3Mz4STPTBbUPvSy8b0GW_PYHQMcP6kXBDKIqhANAnVJINu3mdJk4mrEnG8-RSmR9SBa59z9qjRSxIVSEJapVWMSgGZzLHC3EVnib3-P3n1PnJyewKHVzR2tEhC5qWkLkJlXZl-6ETTap3GZGhSZCS6Wm9jEVAHx0nHwMTi6TNkVsw";
                width = 1080;
            }
        );
        "place_id" = ChIJqf1X7LyEh0gRK7GrZbR1qlI;
        reference = "CmRbAAAAoIW6Uer6wFdg9f9c_kRg0s5Wc-6wyUwg49CWQtn9hphJTfCqmidaP_unuejhxZBS_hChwfTHYWsspU7nOOFZx08cmzQ9bAW7cTp1N7vxepNfqR1YNybBBtB4romQAZO7EhCfxI62ia7XGtVPIyEPRSIPGhR4HnxB4lrDp1o4daDSipUAvFoG4Q";
        scope = GOOGLE;
        types =         (
            store,
            parking,
            "car_repair",
            "point_of_interest",
            establishment
        );
        vicinity = "Bridge Street, Galashiels";
    },
        {
        geometry =         {
            location =             {
                lat = "55.827528";
                lng = "-4.041783";
            };
        };
        icon = "https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png";
        id = 993dd6caf6e87b27c95b597170f82fc535db8464;
        name = "Scania Truck Rental";
        photos =         (
                        {
                height = 416;
                "html_attributions" =                 (
                    "<a href=\"https://maps.google.com/maps/contrib/111565851399356378888\">Ian McCully</a>"
                );
                "photo_reference" = "CmRdAAAAgxB25gl4CRnm6PENE9QPRq0WqPqIFUQCrvz7eOWsirTLMLZM_3gd_plKy9teW9AQdDIIZ3Ikmz96ADPiPD-wtDRvjDFMZl274q1HuA4zg8gVNi6QggypXkSPDdOdrfxUEhCf_qaIvJK0_iWgvnmT-TjcGhSRvsf9XiE5hkqcgwQdbKTm7oI5FA";
                width = 640;
            }
        );
        "place_id" = "ChIJ0YTxdlVqiEgRlNZz-R6gs9M";
        reference = "CnRnAAAAGNBVd-2Rzx_pF8lzxZ5WsI1qC8752BhlsKAXwS36PkmNVCZ4VQkH2FjmRDJ3swxoGLfJ0YmG4Cr1MACDFNaPSv0QdBo5zjIXQyRfytk77g2g0XVspPR7IhO9mQpuQHNCA-DDp5m1ph_ry1W3kt8IahIQiW-loOYmR9yACbxLie-eyhoUQF04W9ZNAeasiM5OqTqPlyDn6g8";
        scope = GOOGLE;
        types =         (
            parking,
            "car_repair",
            "point_of_interest",
            establishment
        );
        vicinity = "Melford Road, Bellshill";
    },
        {
        geometry =         {
            location =             {
                lat = "55.778158";
                lng = "-4.053103";
            };
        };
        icon = "https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png";
        id = 5b4e2e7beef36bc21e795144d512adb9cbc9ba54;
        name = "National Tyres and Autocare";
        "opening_hours" =         {
            "open_now" = 1;
            "weekday_text" =             (
            );
        };
        photos =         (
                        {
                height = 631;
                "html_attributions" =                 (
                    "<a href=\"https://maps.google.com/maps/contrib/100159584019554234022\">National Tyres and Autocare</a>"
                );
                "photo_reference" = "CmRdAAAALn7YnxOv_yKF3Sfkau09mJ1T7aY_L7La0E_2dxN9AGndS6evIYUPWCvYrQgSxD6Y69IsdGhkh08iY4gX0-YgXrbdtD0OBW6y8AjwVjYA34FLAAH9c122Kr_ImAGAmogREhDUOxeBxKmpZPcawyxxfnC9GhTJNNzPhS1xvgh_XPBXGOdhFhFgpQ";
                width = 789;
            }
        );
        "place_id" = ChIJrVjMcTMViEgRqc4gOlJfoDs;
        reference = "CnRuAAAAoOOZVebI5pz8rifXu3_n9RbZv0sobjodbPcP1DhknZcwTuZ_zCjch7l3D0tPqSO21S4wQlhYuH6tOrgBzHwkYBcRMS2-XP5r234IevwkdYV04gAk4BPBfuJMQIyrvASsDtRN9LJkPp8By7OleSyyqhIQco-kf732PwomY9loLvEtbBoUc2ZZKVbvMIYk0pVeFQronor3UM8";
        scope = GOOGLE;
        types =         (
            store,
            parking,
            "car_repair",
            "point_of_interest",
            establishment
        );
        vicinity = "Peacock Cross, Almada Street, Hamilton";
    }

2015-10-30 12:16:05.573 GooglePlaces[17141:989254]  name Yosemite National Park

The header file Where currentCenter is defined 定义currentCenter的头文件

    #import <UIKit/UIKit.h>
    #import <MapKit/MapKit.h>
    #import <CoreLocation/CoreLocation.h>
    #define kGOOGLE_API_KEY @"the key here"

    @interface AboutPlaceViewController : UIViewController <MKMapViewDelegate , CLLocationManagerDelegate>
    {
        CLLocationManager *locationManager;
        CLLocation *location;
// Where Current Centre is defined
        CLLocationCoordinate2D currentCentre;
        int currenDist;
        BOOL firstLaunch;

    }

    @property (weak, nonatomic) IBOutlet UILabel *placeLabell;

    @end

The Implementation file 实施文件

#import "AboutPlaceViewController.h"
#import "ViewController.h"

@interface AboutPlaceViewController ()

@end

@implementation AboutPlaceViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    locationManager = [[CLLocationManager alloc]init];
    locationManager.delegate = self;
    [locationManager setDistanceFilter:kCLDistanceFilterNone];
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    [locationManager startUpdatingLocation];
     location = [locationManager location];
    //Do any additional setup after loading the view.
    NSDictionary *jsonDic = [[NSDictionary alloc]init];
    [self getApiResponse:&jsonDic];
    NSLog(@"jsonDic %@",jsonDic);
    NSDictionary *resultDic = [jsonDic[@"results"] objectAtIndex:0];
    NSString *name = resultDic[@"name"];
    NSLog(@" name %@", name);
    self.placeLabell.text = name;
 }
-(void)getApiResponse:(NSDictionary**)dataDictionary
 {
    // Where i dig into the Json array one example provided above
    NSDictionary *responseDict  = [[NSDictionary alloc]init];
    responseDict = [responseDict valueForKey:@"geometry"];
     NSArray *responseArray = [responseDict valueForKey:@"location"];
    NSDictionary *dict;
    // The for loop it doesnt go inside the for loop when debugging
    for(int i = 0; i< [responseDict count]; i++){
        dict = [responseArray objectAtIndex:i];
        NSLog(@"- %@",[responseArray objectAtIndex:i]);
     }
    // Where I declare but it returns nil :(
    currentCentre.latitude = [dict[@"lat"]doubleValue];
    currentCentre.longitude = [dict[@"lng"]doubleValue];

    NSString *api_key = kGOOGLE_API_KEY;
    NSString *urlString = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=50&types=%@&sensor=true&key=%@",currentCentre.latitude   , currentCentre.longitude,[NSString stringWithFormat:@"%i", currenDist],api_key];
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLResponse *response;
    NSError *error = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:
                    request returningResponse:&response error:&error];

    NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

    dataDictionary = [[NSDictionary alloc]initWithDictionary:jsonObject copyItems:YES];
}


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

The responseDict and the responseArray are also returning nil. responseDict和responseArray也返回nil。

The currentCenter is returning nil and when I debug the code it doesn't go into the for loop. currentCenter返回nil,当我调试代码时,它不会进入for循环。 I have looked into the json format to find. 我调查了json格式以查找。

First on all: You have the following line: 首先:您有以下一行:

 location = [locationManager location];

 You call the location straight after you initialise the manager.
 If you look at the location method description it says:

/*
 *  location
 *  
 *  Discussion:
 *      The last location received. Will be nil until a location has been received.
 */
 @property(readonly, nonatomic, copy, nullable) CLLocation *location;

IE you should wait till the first location has been received. IE浏览器,您应该等到收到第一个位置。 Your class needs to implement CLLocationManagerDelegate and override: 您的类需要实现CLLocationManagerDelegate并重写:

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations

Make sure that you requestAlwaysAuthorization before you access the user location 在访问用户位置之前,请确保您请求“始终授权”

Moreover, What are you trying to do in this line? 此外,您打算在这方面做什么?

 NSDictionary *responseDict = [responseDict  valueForKey:@"geometry"];

You are basically defining the dictionary and use it straight away. 您基本上是在定义字典并立即使用它。

Anamica first of all you need to get the latitude and longitude value correctly.If you don not get that,you can't get other details by passing latitude and longitude values. 首先,您需要正确获取Anamica的纬度和经度值。否则,您无法通过传递纬度和经度值来获取其他详细信息。

Getting Latitude and longitude values from your response 从响应中获取经度和纬度值

NSString *lataddr=[[[responseDict objectForKey:@"geometry"]objectForKey:@"location"]objectForKey:@"lat"];
NSString *longaddr=[[[responseDict objectForKey:@"geometry"]objectForKey:@"location"]objectForKey:@"lng"];

Then pass these strings to your url.Now you can get the response without nil. 然后将这些字符串传递给您的url,现在您可以获得没有nil的响应。

Also please remove below coding from your part 也请从您的部分中删除以下编码

NSArray *responseArray = [responseDict valueForKey:@"location"];
NSDictionary *dict;
// The for loop it doesnt go inside the for loop when debugging
for(int i = 0; i< [responseDict count]; i++){
    dict = [responseArray objectAtIndex:i];
    NSLog(@"- %@",[responseArray objectAtIndex:i]);
 }
// Where I declare but it returns nil :(
currentCentre.latitude = [dict[@"lat"]doubleValue];
currentCentre.longitude = [dict[@"lng"]doubleValue];

instead of these part, you need to add 代替这些部分,您需要添加

NSString *lataddr=[[[responseDict objectForKey:@"geometry"]objectForKey:@"location"]objectForKey:@"lat"];
NSString *longaddr=[[[responseDict objectForKey:@"geometry"]objectForKey:@"location"]objectForKey:@"lng"];

currentCentre.latitude = [lataddr doubleValue];
currentCentre.longitude = [longaddr doubleValue];

Above code for getting only single latitude and longitude value. 上面的代码仅获取单个纬度和经度值。

Now if you want to get the multiple latitude and longitude values for showing in map 现在,如果要获取多个纬度和经度值以显示在地图中

NSMutableArray *arrayLat = [[NSMutableArray alloc]init];
NSMutableArray *arrayLng = [[NSMutableArray alloc]init];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil]; //This is for actually you are getting response to dict.
NSArray *arrayResponse = [dict copy];
NSLog(@"The response is - %@",arrayResponse);
for(int i=0;i<[arrayResponse count];i++)
{
   NSString *lataddr=[[[[[arrayResponse objectAtIndex:i]valueForKey:@"geometry"]valueForKey:@"location"]valueForKey:@"lat"];
   NSString *longaddr=[[[[[arrayResponse objectAtIndex:i]valueForKey:@"geometry"]valueForKey:@"location"]valueForKey:@"lng"];

   [arrayLat addObject:lataddr];
   [arrayLng addObject:longaddr];
}
for(int j=0;j<[arrayLat count];j++)
{
  currentCentre.latitude = [[arrayLat objectAtIndex:j] doubleValue];
  currentCentre.longitude = [[arrayLng objectAtIndex:j] doubleValue];
  NSString *api_key = kGOOGLE_API_KEY;
  NSString *urlString = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=50&types=%@&sensor=true&key=%@",currentCentre.latitude   , currentCentre.longitude,[NSString stringWithFormat:@"%i", currenDist],api_key];
  NSURL *url = [NSURL URLWithString:urlString];
  NSURLRequest *request = [NSURLRequest requestWithURL:url];
  NSURLResponse *response;
  NSError *error = nil;
  NSData *data = [NSURLConnection sendSynchronousRequest:
                request returningResponse:&response error:&error];

  NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

  dataDictionary = [[NSDictionary alloc]initWithDictionary:jsonObject copyItems:YES];

}

All the best Anamica:-) 最好的Anamica :-)

NSDictionary *responseDict  = [[NSDictionary alloc]init];
responseDict = [responseDict valueForKey:@"geometry"];

These two lines of code are utter nonsense. 这两行代码完全是胡说八道。 Throw away any thought of what you think what these do lines should do , but look at them and figure out what they are doing. 抛开对这些线路应该做什么的想法,但要看一下并弄清楚它们在做什么。 How code responseDict possibly be anything other than nil after executing these two lines? 执行这两行代码后,responseDict怎么可能不是nil呢?

As I found(If I am right) you are trying to fetch values from son data form server. 正如我发现的(如果我是对的),您正在尝试从子数据表单服务器中获取值。

You can use NSJsonSerilazation for getting data from NSData. 您可以使用NSJsonSerilazation从NSData获取数据。 Below is only a demo code for getting values 以下仅是用于获取值的演示代码

  NSData *yourDataFromServer;
    NSError*error;
    id records=  [NSJSONSerialization JSONObjectWithStream:yourDataFromServer options:NSJSONReadingMutableContainers error:&error];
    if (error!=nil)
    {
        if ([records isKindOfClass:[NSArray class]])  //Since you are getting Array Of Dictionary
        {
            NSDictionary *dictAtZeroIndex = records[0];
            NSDictionary *latLonDict= [dictAtZeroIndex valueForKey:@"geometry"];  //Again it will be a dictionary. For safety, Here you can again check wheter you are getting dictionary or array using "isKindOfClass"

        }
    }
    else{
        NSLog(@"error is :%@",error.localizedDescription);
    }

"yourDataFromServer" is NSData object coming from server. “ yourDataFromServer”是来自服务器的NSData对象。 Might be helpful. 可能会有所帮助。 Let me know if you are having any query. 让我知道您是否有任何疑问。 Use valueForKey with "latLonDict" for getting lat-lon values. 将valueForKey与“ latLonDict”一起使用以获取经纬度值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM