Search code examples
iphonensurl

Bad URL when creating NSURL


I am making request on server , having spaces in URL

http://xxxxxxxx.com/api/api.php?func=showAllwedsdwewsdsd&params[]=Saudi%20Arab&params[]=all

I was getting the error Bad URL so ,

I used

   downloadURL = [downloadURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

but due this I am getting strange URL as

 http://sdsdsdsdsdsd.com/api/api.php?func=showAllsdsd&params5262721536=Saudi              0X0P+0rabia&params5 8288=All

I am also using

  downloadURL= [downloadURL stringByReplacingOccurrencesOfString:@" " withString:@"%20"];

but again strange url like

     http://xxxxxxxxx.com/api/api.php?func=showsdsdsd&params[]=Saudi 0X1.240DC0D824P-807rabia&params[]=All

Please help how can I solve this issue

Edit Pasting Big portion of code

   PropertyXMLDownloader *download=[[PropertyXMLDownloader alloc]init];
  [download setDelegate:self];
   firstAppDelegate *del=(firstAppDelegate *)[[UIApplication sharedApplication]delegate];
   NSLog(@"Country is %@",del.country);
   NSLog(@"State is %@",del.state);
//  del.country=[del.country stringByReplacingOccurrencesOfString:@" " withString:@"%20"];

   NSString *downloadURL=[NSString stringWithFormat:@"http://xxxxxxxx.com/api/api.php?func=showAll&params[]=Saudi Arabia&params[]=%@",@"all"];
      // downloadURL= [downloadURL stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
       //downloadURL = [downloadURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

   NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@" "];
   downloadURL = [[downloadURL componentsSeparatedByCharactersInSet: doNotWant]    componentsJoinedByString:@"%20"];


    NSLog(downloadURL); 
    [download startDownloading:downloadURL];

Solution

  • try this.

    NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@" "];
    downloadURL = [[downloadURL componentsSeparatedByCharactersInSet: doNotWant]   componentsJoinedByString:@"%20"];