[英]NSURL is null while NSString is correct in Objective-C
我有一個包含url的NSString
,當我使用NSString
分配NSURL
時,NSURL輸出(null)。 這是因為url中存在一些非法字符,如果不對包含url的NSString
進行編碼,則NSURL
無法讀取。
NSString *u = [incomingUrlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:u];
NSLog(@"INCOMINGURLSTRING: %@" , u);
NSLog(@"URL: %@" , url);
輸出是:
INCOMINGURLSTRING: /url/path/fileName_blå.pdf
URL: (null)
incomingUrlString包含挪威語字母“å”,我認為這是NSURL
的原因(null)
我也試過這個:
NSString *trimmedString = [file stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)trimmedString, NULL, (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ", kCFStringEncodingUTF8);
NSLog(@"TRIMMEDSTRING: %@" , trimmedString);
NSLog(@"ENCODEDSTRING: %@" , [encodedString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]);
NSURL *url = [NSURL URLWithString:encodedString];
NSLog(@"URL: %@" , url);
這里的輸出是:
TRIMMEDSTRING: /url/path/fileName_blå.pdf
ENCODEDSTRING: /url/path/fileName_blå.pdf
URL: %2Furl%2FPath%2FfileName_bl%C3%A5.pdf
我的目標是將URL加載到UIWebView
。 它適用於除此之外的所有其他傳入URL,除文件名外,它們看起來都相同。 這是唯一一個涉及非法角色的人。 但我必須找到一種方法來編碼,因為將來會有更多的文件包含“æ”,“ø”或“å”。
根據網址標准,我知道輸出看起來不正確,我是故意做的。 由於安全原因,我無法使用http:// blah blah顯示正確的URL。
有人可以幫忙嗎?
您用於對字符串中的字符進行百分比編碼的方法也會轉義合法的URL字符。 如果你編碼一個URL參數,這是合適的,在這種情況下,雖然最好簡單地使用stringByAddingPercentEscapesUsingEncoding:
因為它stringByAddingPercentEscapesUsingEncoding:
了作為URL結構(':','/'等)一部分的字符完好無損:
NSString *u = @"http://example/path/fileName_blå.pdf";
u = [u stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:u];
NSLog(@"%@", url); // http://example.com/path/fileName_bl%C3%A5.pdf
如果您的URL是文件路徑,則必須使用+ (id)fileURLWithPath:(NSString *)path
。 對於URLWithString:
方法,String必須包含類似file://
或http://
。
不推薦使用stringByAddingPercentEscapesUsingEncoding
。
新方法(iOS 7+)是這樣做的:
NSString *encoded = [raw stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLPathAllowedCharacterSet];
文件路徑由https://tools.ietf.org/html/rfc8089定義。
關鍵部分是允許角色.
和/
和不允許%
。 CharacterSet.urlPathAllowed
符合要求。
用你的例子輸出:
incomingString:/url/path/fileName_blå.pdf
encodedString:/url/path/fileName_bl%C3%A5.pdf
URL:/url/path/fileName_bl%C3%A5.pdf
我還發現,對於一些北歐角色,NSISOLatin1StringEncoding更適合。
- (void) testEncoding {
NSString * urlString = @"http://example/path/fileName_blå.pdf";
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSISOLatin1StringEncoding];
NSURL * url = [NSURL URLWithString:urlString];
NSLog(@"URL: %@", url);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.