问题
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]];
回答1:
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).
回答2:
You are using NSASCIIStringEncoding
to encode a unicode string, thus you get weird charaters.
Use NSUTF8StringEncoding
like:
NSString *queryParemeters = [textField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *request = [NSString stringWithFormat:@"http://www.xxxxxxxx.com/CCWCF.svc/MethodName/%@", queryParemeters];
NSLog(@"Encoded URL :%@", request);
NSURL *URL = [NSURL URLWithString:request];
回答3:
I believe it's the unicode characters.
Convert them using stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding
:
NSString *text = @"ATAŞEHİR";
NSString *convertedText = [text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *request = [NSString stringWithFormat:@"http://www.xxxxxxxx.com/CCWCF.svc/MethodName/%@", convertedText];
来源:https://stackoverflow.com/questions/15291197/nsurl-always-returns-nil