NSURL Always Returns Nil

我们两清 提交于 2020-01-24 15:06:18

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!