美文网首页iOS官方文档翻译iOS文档翻译iOS官方文档
编码和解码URL数据 <- URL会话编程指南

编码和解码URL数据 <- URL会话编程指南

作者: raingu24 | 来源:发表于2017-07-11 20:49 被阅读4次

    想要对部分URL字符串进行百分号编码,请使用NSString的stringByAddingPercentEncodingWithAllowedCharacters:方法,给URL组件或子组件传递合适的字符集:

    • User: URLUserAllowedCharacterSet
    • Password: URLPasswordAllowedCharacterSet
    • Host: URLHostAllowedCharacterSet
    • Path: URLPathAllowedCharacterSet
    • Fragment(片段): URLFragmentAllowedCharacterSet
    • Query(查询): URLQueryAllowedCharacterSet

    重要:不要使用stringByAddingPercentEncodingWithAllowedCharacters:来编码整个URL字符串,因为每个URL组件或子组件对于有效字符都有不同的规则。

    例如,想要对包含在URL片段中的UTF-8字符串进行百分号编码,请执行如下操作:

    NSString *originalString = @"color-#708090";
    
    NSCharacterSet *allowedCharacters = [NSCharacterSet URLFragmentAllowedCharacterSet];
    
    NSString *percentEncodedString = [originalString stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
    
    NSLog(@"%@", percentEncodedString"); // prints "color-%23708090"
    
    let originalString = "color-#708090"
    
    let allowedCharacters = NSCharacterSet.urlFragmentAllowed
    
    let encodedString = originalString.addingPercentEncoding(withAllowedCharacters: allowedCharacters)
    
    print(encodedString!) // prints "color-%23708090"
    

    如果你想对URL组件进行百分号编码,使用NSURLComponents把URL分拆成它的组成部分,并访问相关的属性。

    例如,想要得到URL片段百分号编码的UTF-8字符串值,请执行以下操作:

    NSURL *URL = [NSURL URLWithString:@"https://example.com/#color-%23708090"];
    
    NSURLComponents *components = [NSURLComponents componentsWithURL:URL resolvingAgainstBaseURL:NO];
    
    NSString *fragment = components.fragment;
    
    NSLog(@"%@", fragment); // prints "color-#708090"
    
    let url = URL(string: "https://example.com/#color-%23708090")!
    
    let components = URLComponents(url: url, resolvingAgainstBaseURL: true)!
    
    let fragment = components.fragment!
    
    print(fragment) // prints "color-#708090"
    

    相关文章

      网友评论

        本文标题:编码和解码URL数据 <- URL会话编程指南

        本文链接:https://www.haomeiwen.com/subject/ixzmhxtx.html