NSURL

URL(统一资源定位符) 是一种 URI,URN(统一资源名称) 也是一种 URI,所以 URI (统一资源标志符)可被视为定位符,名称或两者兼备

URL Encode

[iOS-Foundation] NSURL
URL采用ASCII编码格式,所以不支持如中文等非ASCII码字符,另外URL中保留的分隔符号(?、&、=等)也无法作为内容,否则会引起歧义。
这就需要通过编码,用安全的字符来表示这些不符合要求的字符,格式是%加两位安全字符,所以 URL 编码也称为百分号编码。

//Encode编码
NSString *urlString = @"?";
NSString *encodedString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
//encodedString值为 %3F
//替换不符合要求UTF-8编码为百分号编码字符
@interface NSCharacterSet (NSURLUtilities)
+ (NSCharacterSet *)URLUserAllowedCharacterSet;
+ (NSCharacterSet *)URLPasswordAllowedCharacterSet;
+ (NSCharacterSet *)URLHostAllowedCharacterSet;
+ (NSCharacterSet *)URLPathAllowedCharacterSet;
+ (NSCharacterSet *)URLQueryAllowedCharacterSet;
+ (NSCharacterSet *)URLFragmentAllowedCharacterSet;
@end
//Unencode解码
+ (NSString *)decodeURLString:(NSString *)URLString {
    // 有时从服务端获取的 URL 中,空格被编码为+, 
    // 而方法- stringByRemovingPercentEncoding只替换百分号编码,
    // 所以要在执行该方法前,先将`+`替换掉(真正的加号字符是被百分号编码的)
    NSString *result = [URLString stringByReplacingOccurrencesOfString:@"+" withString:@" "];
    //替换所有百分号编码为UTF-8编码字符
    result = [result stringByRemovingPercentEncoding];
    return result;
}

NSURL

NSURL苹果官方文档

我们通过NSURL对象来构建一个资源定位符。对于本地文件的资源定位符,我们可以直接操作这些问价你的属性(比如修改文件的的最后修改日期),对于远程资源我们可以将NSURL对象传递给其他API来获取内容,Next About the URL Loading System

URL对象是指向本地文件的首选方案,大多数进行文件数据读写对象都接受一个NSURL对象而不是一个文件路径.例如:可以用文件NSURL获取NSString initWithContentsOfURL:encoding:error:,获取data initWithContentsOfURL:options:error:

你也可以用url资源定位符进行需要的操作,例如在macOSNSWorkspace类和iOSUIApplication类提供的OpenURL:方法来打开一个指定的URL位置

此外,我们可以通过使用粘贴板来对NSURL对象进行引用(AppKit框架的一部分)

NSURL对应Core Foundation中的CFURLRef,我们可以查看Toll-Free Bridging来获取更多类似的与Core Foundation相对应的信息

补充:
Swift提供了URL结构,负责连接NSURL类,可以在 Classes and Structures中查看更多信息

URL结构

一个NSURL对象由两部分组成:一部分是可能为nilbase URL和一部分与base URL有相对关系的字符串relativeString。如果一个NSURL对象没有base部分只有string部分那么它被认为是绝对地址,否则为相对的.

//file:///path/to/user/ as the base URL and folder/file.html
/**
    我们指定 file:///path/to/user/ 为baseURL folder/file 为字符串部分
*/
NSURL *baseURL = [NSURL fileURLWithPath:@"file:///path/to/user/"];
NSURL *URL = [NSURL URLWithString:@"folder/file.html" relativeToURL:baseURL];
NSLog(@"absoluteURL = %@", [URL absoluteURL]);//file:///path/to/user/ as the base URL and folder/file.html
/**
    这个URL的
    absoluteString:  file:///file:/path/to/folder/file.html
    baseURL:  file:///file:/path/to/user
    relativeString: folder/file.html
*/

对于一个URL我们可以将其分为很多部分,例如一个url如下:
https://johnny:p4ssw0rd@www.example.com:443/script.ext;param=value?query=value#ref

Component Value
scheme https
user johnny
password p4ssw0rd
host www.example.com
port 443
path /script.ext
pathExtension ext
pathComponents ["/", "script.ext"]
parameterString param=value
query query=value
fragment ref

NSURL也提供了很多属性让我们来获取每部分

书签以及安全范围