开发者

Problem in creating url string

    NSString *sttr=[[NSString alloc]init ];开发者_运维知识库
    NSURL *jsonURL;
    NSString *strurl;

    sttr =@"|7 Harvard Drive, Plymouth, MA, 02360, |9121 SW 174th St., Miami, FL, 33157, |7 Harvard Drive, Plymouth, MA, 02360, |";
    NSLog(@"StringToSend=%@",sttr);
    strurl = [[NSString alloc]initWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%@&destination=%@&waypoints=optimize:true%@&sensor=false&mode=driving",sttr];

But the when i debug then strurl is always nil .

Whats the issue here is due to spaces in the location name .How can i haandle that .

Thanks in advance


You can separate the components of the string to individual strings and then pass it to the necessary url string.

Try this and see if it works

NSURL *jsonURL;
NSString *strurl;
NSString *sourceString = @"|7 Harvard Drive, Plymouth, MA, 02360, |9121 SW 174th St.";
NSString *destString = @"Miami, FL, 33157, |7 Harvard Drive, Plymouth, MA, 02360, |";
strurl = [[NSString alloc]initWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%@&destination=%@ |&waypoints=optimize:true%@&sensor=false&mode=driving",sourceString,destString,@" "];
NSLog(@"%@",strurl);


From your code the strurl shouldn't be nil.

By the way: You have a memory leak because @"some string" gives you an autoreleased object and the memory you retained in NSString *sttr=[[NSString alloc]init ]; is never released.


Change ur code.

strurl = [[NSString alloc]initWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%@&destination=%@&waypoints=optimize:true%@&sensor=false&mode=driving",sttr,sttr,sttr];


You should use same number of "%@" and the variables your pass change your code something like this -

strurl = [[NSString alloc]initWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%@&destination=%@&waypoints=optimize:true%@&sensor=false&mode=driving",sttr,destinationStr,anotherVar];

Also I am not getting why you have a "%@" here -

waypoints=optimize:true%@&s

if you are fetching contents from this url that may be nil you should encode the url string before creating a NSURL from it .. use this function -

-(NSString *) URLEncodeString:(NSString *) str
{

    NSMutableString *tempStr = [NSMutableString stringWithString:str];
    [tempStr replaceOccurrencesOfString:@" " withString:@"+" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [tempStr length])];


    return [[NSString stringWithFormat:@"%@",tempStr] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜