Nsstring Encoding Returns Nil on Url Content

NSString encoding returns nil on url content

The problem there as already mentioned by rmaddy it is the encoding you are using. You need to use NSASCIIStringEncoding.

if let url = URL(string: "https://www.google.com") {
URLSession.shared.dataTask(with: url) {
data, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let data = data, error == nil,
let urlContent = String(data: data, encoding: .ascii)
else { return }
print(urlContent)
}.resume()
}

Or taking a clue from Martin R you can detect the string encoding from the response:

extension String {
var textEncodingToStringEncoding: Encoding {
return Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(self as CFString)))
}
}

if let url = URL(string: "https://www.google.com") {
URLSession.shared.dataTask(with: url) {
data, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let data = data, error == nil,
let textEncoding = response?.textEncodingName,
let urlContent = String(data: data, encoding: textEncoding.textEncodingToStringEncoding)
else { return }
print(urlContent)
}.resume()
}

NSURL URLWithString:myString returns Nil?

Your URL is nil because it contains special chars, use this following function to encode your url parameters before using them in URL -

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

NSURL URLWithString returns nil

yes what was wrong in my string were many unidentified characters due to copying from internet site, if anyone of the reader facing this issue can copy and paste your string as see the count. And confirm.
Thanks

iOS NSURL returning nil on valid URL

The problem is that you need to percent-encode your values in the URL string. When it’s received by the server, it will decode this percent-encoded string in the URL into the desired value.

But rather than percent-encoding yourself, you can use NSURLComponents. For example, if you want a to have the value of @"1\\tb", you can do:

NSURLComponents *components = [NSURLComponents componentsWithString:@"http://localhost:8080"];
components.queryItems = @[
[NSURLQueryItem queryItemWithName:@"a" value:@"1\\tb"],
[NSURLQueryItem queryItemWithName:@"b" value:@"2"]
];
NSURL *url = components.URL;

Yielding:

http://localhost:8080?a=1%5Ctb&b=2

Or, if you wanted it to have the tab character in the value associated with a (i.e. %09):

NSURLComponents *components = [NSURLComponents componentsWithString:@"http://localhost:8080"];
components.queryItems = @[
[NSURLQueryItem queryItemWithName:@"a" value:@"1\tb"],
[NSURLQueryItem queryItemWithName:@"b" value:@"2"]
];
NSURL *url = components.URL;

Yielding:

http://localhost:8080?a=1%09b&b=2

It just depends upon whether your server is expecting two characters, the \ followed by t (the first example) or the single \t character (the second example). Either way, the respective use of NSURLComponents will take care of the percent-encoding for you, and your server will decode it.


For what it’s worth, the one caveat is the + character, which NSURLComponents won’t percent-encode for you (because, technically, a + character is allowed in a URL query). The problem is that the + character is interpreted as a space character by most web servers (per the x-www-form-urlencoded spec). If you need to pass a literal + character, you might want to replace those + characters, as advised by Apple:

NSURLComponents *components = [NSURLComponents componentsWithString:@"http://localhost:8080"];
components.queryItems = @[
[NSURLQueryItem queryItemWithName:@"q" value:@"Romeo+Juliet"]
];
components.percentEncodedQuery = [components.percentEncodedQuery stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
NSURL *url = components.URL;

NSURL gives nil when Arabic words are passed through URL

Try this:

NSString *string = @"http://192.168.227.1/student/Service1.svc/insertTasbeeh/سُبْحَانَ اللّهِ/1000";

NSLog(@"url with string! %@", [NSURL URLWithString:string]);
NSLog(@"url with escaped string! %@", [NSURL URLWithString:
[string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]);

Hope this helps you !

Update for decoding url:

NSURL *url = [NSURL URLWithString:
[string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *myString = url.absoluteString; // or url.relativeString;

NSString* str = [myString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

Read string from a file return nil

As mentioned, Cocoa error 261 is NSFileReadInapplicableStringEncodingError which means the encoding of file is different than what you are passing in the API.

For Hebrew language encoding, try this answer

NSString* content = [[NSString alloc] initWithContentsOfFile:path encoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingWindowsHebrew) error:&err];

Hope that helps!

NSURL Always Returns Nil

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

Why my return is nil but if i press the url in chrome/safari, i can get data?

The text you try to get is probably not UTF-8, try with another encoding, like this for example:

let myString = NSString(data: data, encoding: NSASCIIStringEncoding)

Update: read Martin R's answer for how to find the right encoding.

URLWithString: returns nil

You need to escape the non-ASCII characters in your hardcoded URL as well:

//localisationName is a arbitrary string here
NSString* webName = [localisationName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* stringURL = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@,Montréal,Communauté-Urbaine-de-Montréal,Québec,Canadae&output=csv&oe=utf8&sensor=false", webName];
NSString* webStringURL = [stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:webStringURL];

You can probably remove the escaping of the localisationName since it will be handled by the escaping of the whole string.



Related Topics



Leave a reply



Submit