iphone - 在 for 循环中使用不同的 url 多次发送 NSURLConnection 请求

标签 iphone ios for-loop nsurlconnection geocoding

我有一个地址数组,需要使用 Google 的地理编码 api 将其转换为纬度/经度。我将地址和城市输入 Google 地理编码 URL,这形成了正确的连接 URL。

基本上我希望能够使用 for 循环创建多个 NSURLConnection 请求,返回多个响应。

-(void)setString{
 for (int i = 0; i < [businessArray count]; i ++)
{         
NSString *address = [addressArray objectAtIndex:0];
NSString *city = [locationDict valueForKey:@"city"];
NSString *geocodeURL = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?address=%@,+%@,&sensor=true", address, city];
    geocodeURL = [geocodeURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:geocodeURL]
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:10];
    NSLog(@"%@", request);
    geoCodeConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];


    if (geoCodeConnection)
    {
        responseData = [NSMutableData data];
        connectionIsActive = YES;
        NSLog(@"connection active");

    } else {
        NSLog(@"connection failed");
        connectionIsActive = NO;
    }

}
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{


    NSString *responseString    = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    NSError *jsonError          = nil;

    SBJsonParser *json          = [[SBJsonParser alloc] init];

    NSDictionary *parsedJSON    = [json objectWithString:responseString error:&jsonError];

    NSString *lat= [[[[parsedJSON valueForKey:@"results"] valueForKey:@"geometry"] valueForKey:@"location"] valueForKey:@"lat"];
    NSString *lng= [[[[parsedJSON valueForKey:@"results"] valueForKey:@"geometry"] valueForKey:@"location"] valueForKey:@"lng"];

    NSLog(@"lat = %@ long= %@", lat, lng);
    connectionIsActive          = NO;
    [geoCodeLatArray addObject:lat];
    [geoCodeLngArray addObject:lng];
    NSLog(@"geoCodeArrayLat: %@", geoCodeLatArray);


}

现在代码仅返回最后一个地址的纬度和经度。如何使用 JSON 发送多个请求并返回多个响应?

最佳答案

试试这个,我正在使用这个,

for(int i=0;i< businessArray.count;i++)
{
    NSString *address = [addressArray objectAtIndex:i];
    NSString *city = [locationDict valueForKey:@"city"];
    NSString *address = [NSString stringWithFormat:@"%@,%@", address, city];

    CLLocationCoordinate2D location = [self geoCodeUsingAddress:address];
    // then here store the location.latitude in lat array and location.longitude in long array.
}

- (CLLocationCoordinate2D) geoCodeUsingAddress:(NSString *)address
{
    NSString *esc_addr =  [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *req = [NSString stringWithFormat:@"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%@", esc_addr];

    NSDictionary *googleResponse = [[NSString stringWithContentsOfURL: [NSURL URLWithString: req] encoding: NSUTF8StringEncoding error: NULL] JSONValue];

    NSDictionary    *resultsDict = [googleResponse valueForKey:  @"results"];
    NSDictionary   *geometryDict = [resultsDict valueForKey: @"geometry"];
    NSDictionary   *locationDict = [geometryDict valueForKey: @"location"];

    NSArray *latArray = [locationDict valueForKey: @"lat"];
    NSString *latString = [latArray lastObject];

    NSArray *lngArray = [locationDict valueForKey: @"lng"];
    NSString *lngString = [lngArray lastObject];

    CLLocationCoordinate2D location;
    location.latitude = [latString doubleValue];
    location.longitude = [lngString doubleValue];

    return location;
}

更新上述函数:

- (CLLocationCoordinate2D) geoCodeUsingAddress:(NSString *)address
{
    double latitude = 0, longitude = 0;
    NSString *esc_addr =  [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *req = [NSString stringWithFormat:@"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%@", esc_addr];
    NSString *result = [NSString stringWithContentsOfURL:[NSURL URLWithString:req] encoding:NSUTF8StringEncoding error:NULL];
    if (result) {
        NSScanner *scanner = [NSScanner scannerWithString:result];
        if ([scanner scanUpToString:@"\"lat\" :" intoString:nil] && [scanner scanString:@"\"lat\" :" intoString:nil]) {
            [scanner scanDouble:&latitude];
            if ([scanner scanUpToString:@"\"lng\" :" intoString:nil] && [scanner scanString:@"\"lng\" :" intoString:nil]) {
                [scanner scanDouble:&longitude];
            }
        }
    }
    CLLocationCoordinate2D location;
    location.latitude = latitude;
    location.longitude = longitude;
    return location;
}

这对我有用。

关于iphone - 在 for 循环中使用不同的 url 多次发送 NSURLConnection 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17519839/

相关文章:

ios - XCode5 中两个 UITableView 之间的奇怪纠缠

iphone - 通过另一个实体属性设置核心数据实体属性

ios - 渐变子层不透明度

ios - 第二个带有 UISearchController 的推送 View Controller 在 UINavigationBar 中没有接收到触摸

ios - Safari Web 检查器在调试 iPhone 时不显示元素和样式面板

iphone - 如何在 iOS 上创建图库

iOS应用商店: How to share analytics data of selected App Store/region?

r - 为什么要在 R 中复制列表?

java - 查找给定整数的因子

java - String.equals 与 foreach 和 for 循环