如何在json urlstring中包含变量

时间:2012-10-19 07:52:20

标签: iphone ios json

如何将值替换为变量。

 NSURLRequest *request = [NSURLRequest requestWithURL: [NSURL
 URLWithString:@"https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=500&types=food"]];

我想替换

1) -33.867
2) 151
3) 500
4) food

使用URLWithString中的变量。 提前谢谢。

3 个答案:

答案 0 :(得分:2)

float latitude = -33.8670522f;
float longitude = 151.1957362f;
int radius = 500;
NSString* types = @"food";

NSString* urlString = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=%d&types=%@", latitude, longitude, radius, type];
NSURL* url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

我不确定我是否有正确的纬度/经度,或者是否必须相反,但无论如何,你明白了! ;)

答案 1 :(得分:2)

为什么不创建某种工厂方法:

- (NSURL *) URLForPlaceForType:(NSString *)typ atLat:(double)lat lng:(double)lng radius:(NSInteger)radius {
    NSString *path = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=%d&types=%@", lat, lng, radius, type];
    return [NSURL URLWithString:path]; 
}

答案 2 :(得分:0)

您是否尝试在NSString类引用中找到答案?

Finding Characters and Substrings
– rangeOfCharacterFromSet:
– rangeOfCharacterFromSet:options:
– rangeOfCharacterFromSet:options:range:
– rangeOfString:
– rangeOfString:options:
– rangeOfString:options:range:
– rangeOfString:options:range:locale:
– enumerateLinesUsingBlock:
– enumerateSubstringsInRange:options:usingBlock: