mrugen munshi
mrugen munshi

Reputation: 3607

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

Upvotes: 0

Views: 295

Answers (4)

visakh7
visakh7

Reputation: 26400

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);

Upvotes: 1

Saurabh
Saurabh

Reputation: 22903

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];
}

Upvotes: 0

Shrey
Shrey

Reputation: 1977

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];

Upvotes: 0

dasdom
dasdom

Reputation: 14073

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.

Upvotes: 0

Related Questions