2011-02-17 8 views
1

문제가 있습니다.stringByReplacingOccurrencesOfString이 예상대로 작동하지 않습니다.

Latitude = [TBXML textForElement:lat]; //Latitude & Longitude are both NSStrings 
Longitude= [TBXML textForElement:lon]; 
NSLog(@"LAT:%@ LON:%@",Latitude,Longitude); 
NSString *defaultURL = @"http://api.wxbug.net/getLiveWeatherRSS.aspx?ACode=000000000&lat=+&long=-&unittype=1"; 
newURL = [[defaultURL stringByReplacingOccurrencesOfString:@"+" 
                 withString:Latitude] 
            stringByReplacingOccurrencesOfString:@"-" 
                 withString:Longitude]; 
NSLog(@"%@",newURL); 

을 그리고 여기에 출력입니다 : 여기 내 코드는

LAT:-33.92 LON:18.42 
http://api.wxbug.net/getLiveWeatherRSS.aspxACode=000000000&lat=18.4233.92&long=18.42&unittype=1 

당신이 볼 수 있듯이, 이상한 일이 첨부 된 코드에 일어나고있다. 내가 여기서 뭔가 잘못하고있는거야?

답변

7

경도를 교체하기 전에 문자열은 위도로 대체됩니다 두 -, 따라서 둘 다의가 있음을 시스템이 보는

http://....&lat=-33.92&long=-&... 
       ^  ^

입니다.


예를 들어.

NSString *defaultURL = @"http://....&lat={latitude}&long={longitude}&unittype=1"; 
newURL = [defaultURL stringByReplacingOccurrencesOfString:@"{latitude}" 
               withString:Latitude]; 
newURL = [newURL stringByReplacingOccurrencesOfString:@"{longitude}" 
              withString:Longitude]; 

또는 단순히 +stringWithFormat:을 사용하십시오. 우리가 시작했던 곳

NSString* newURL = [NSString stringWithFormat:@"http://....&lat=%@&long=%@&...", 
               Latitude, Longitude]; 
+0

감사합니다. 지금은 모두 분명합니다. :) 당신이 제안하고 자리 표시자를 더 명확한 가치로 바꿀 때 나는 할 것입니다. 감사! –

3

은 다음과 같습니다

url = @"http://...?ACode=000000000&lat=+&long=-&unittype=1" 
Latitude = @"-33.92" 
Longitude = @"18.42" 

이 그럼 당신은 @"-33.92"으로 @"+"의 모든 항목을 대체 :
url = @"http://...?ACode=000000000&lat=-33.92&long=-&unittype=1" 

이 그럼 당신은 @"18.42"@"-"의 모든 항목을 대체했다. 두 개의 '-'문자가 있습니다. 하나는 lat= 이후이고 하나는 long= 이후입니다. 'lat'다음에 오는 것은 거기에 붙여 넣은 문자열에 -이 있기 때문입니다.

url = @"http://...?ACode=000000000&lat=18.4233.92&long=18.42&unittype=1" 

따라서 최종 결과입니다.

+0

아, 말이 되네. 감사! –

1

당신의 LAT는 부정적입니다. 따라서 -는 두 번 교체됩니다.

2

@KennyTM, BJ Homer 및 madmik3이 정확합니다. 당신의 가치는 두 번 바뀌고 있습니다.

그러나 기술적으로 완전히 다른 방식으로 URL을 구축해야한다 :

NSMutableDictionary *query = [NSMutableDictionary dictionary]; 
[query setObject:@"000000000" forKey:@"ACode"]; 
[query setObject:Latitude forKey:@"lat"]; 
[query setObject:Longitude forKey:@"long"]; 
[query setObject:@"1" forKey:@"unittype"]; 

NSMutableArray *queryComponents = [NSMutableArray array]; 
for (NSString *key in query) { 
    NSString *value = [query objectForKey:key]; 
    key = [key stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]; 
    value = [value stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]; 

    NSString *component = [NSString stringWithFormat:@"%@=%@", key, value]; 
    [queryComponents addObject:component]; 
} 

NSString *queryString = [components componentsJoinedByString:@"&"]; 

NSString *fullURLString = [NSString stringWithFormat:@"http://api.wxbug.net/getLiveWeatherRSS.aspx?%@", queryString]; 
NSURL *newURL = [NSURL URLWithString:fullURLString]; 

(지금은 -stringByAddingPercentEscapesUsingEncoding:의 효과를 무시)

이 더 나은 이유는 그에 따라 HTTP 사양 인 the keys and values in the query of the URLURL encoded이어야합니다. 허락하신다면, 당신은 단순한 키들의 숫자만을 인코딩하고 있습니다. 그러나 그것이 변경되면 URL이 손상 될 수 있습니다. (이 방법의 단점은 키당 하나의 값만 허용한다는 점과 HTTP 사양에서는 여러 값을 지정할 수 있다는 점입니다.) 간략하게하기 위해 나는 이것을 버렸습니다.

몇 가지 문제가 있습니다. 에 -stringByAddingPercentEscapesUsingEncoding:. 자세한 내용은 Objective-c iPhone percent encode a string?을 확인하십시오.

+0

Dave, 멋진 조언. 현재로서는 구현할 필요가 없다고 생각하지만 마음에 두겠습니다. 공유해 주셔서 감사합니다. –

관련 문제