NSString *testurl = @"https://www.lalala.com/xiangce/我的第二本相册/photo22";
url = [NSURL URLWithString:testurl];
如果testurl 字符串中包含中文, 在初始化 NSURL对象时, 是不能成功的, url会为nil
因为url中不能包含中文.
可以使用stringByAddingPercentEscapesUsingEncoding
方法来编码中文;
使用stringByReplacingPercentEscapesUsingEncoding
方法来反编译回中文.
NSString *testurl = @"我的第二本相册";
//编码
testurl = [testurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//反编码
NSString *decodeUrl = [testurl stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@",decodeUrl);
而且, 即使多次编码也没有问题:
NSString *testurl = @"https://www.lalala.com/xiangce/我的第二本相册/photo22
testurl = [testurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
testurl = [testurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
testurl = [testurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
testurl = [testurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
url = [NSURL URLWithString:testurl];