CFURLCreateStringByAddingPercentEscapes 这个函数被废弃了应该用哪个替代具体用法是什么?
在 iOS 9.0 和 macOS 10.11 中,CFURLCreateStringByAddingPercentEscapes 函数已被废弃,推荐使用 NSURLComponents 类的 stringByAddingPercentEncodingWithAllowedCharacters: 方法来替代。
具体使用方法:
- 导入 NSURLComponents 头文件:
#import <Foundation/Foundation.h>
- 创建 NSURLComponents 对象:
NSURLComponents *components = [[NSURLComponents alloc] init];
- 设置 URL 的各个部分:
[components setScheme:@"https"];
[components setHost:@"www.example.com"];
[components setPath:@"/path/to/resource"];
- 对需要编码的字符串进行编码:
NSString *unencodedString = @"hello world";
NSCharacterSet *allowedCharacters = [NSCharacterSet URLQueryAllowedCharacterSet];
NSString *encodedString = [unencodedString stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
其中,allowedCharacters 参数指定了哪些字符不需要编码,常用的包括 URLQueryAllowedCharacterSet、URLHostAllowedCharacterSet 等。
- 将编码后的字符串添加到 URL 中:
[components setQuery:encodedString];
- 获取完整的 URL 字符串:
NSString *urlString = [components string];
原文地址: https://www.cveoy.top/t/topic/bRTk 著作权归作者所有。请勿转载和采集!