Search code examples
iphoneiosnsurl

NSURL Always Returns Nil


I have WCF service and I want to get data from my web service. But URL always returns nil. Why? I want to send parameter to WCF which comes from text field value. For example;

txtfield.text = @"ATAŞEHİR";

What's wrong ?

NSString *request = [NSString stringWithFormat:@"http://www.xxxxxxxx.com/CCWCF.svc/MethodName/%@",txtfield.text];
NSURL *URL = [NSURL URLWithString:[request stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];

I tried different things but result didn't change.

NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.xxxxxxxx.com/CCWCF.svc/MethodName/%@",txtfield.text]];

or:

NSURL *URL = [[NSURL alloc] initWithString:[request stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];

Solution

  • NSString* encodedText = [txtfield.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *request = [NSString stringWithFormat:@"http://www.xxxxxxxx.com/CCWCF.svc/MethodName/%@",encodedText];
    NSURL *URL = [NSURL URLWithString:request];

    On a separate note, [NSString stringByAddingPercentEscapesUsingEncoding:] can be a bit problematic for URL encoding. There is a safer way using Core Foundation. See http://madebymany.com/blog/url-encoding-an-nsstring-on-ios, for example (can't find the SO question).