ios - URLPathAllowedCharacterSet 不编码感叹号

标签 ios objective-c url-encoding

我正在尝试构建一个 url 并确保对路径中的所有特殊字符进行编码,我目前未能这样做,可能是由于对 path 属性的误解NSURLComponents 有效。

NSURLComponents *components = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];

NSURLQueryItem *queryItem = [NSURLQueryItem queryItemWithName: @"queryName" value: @"queryValue"];
components.queryItems = @[queryItem];

//我以为 stringByAddingPercentEncodingWithAllowedCharacters 会编码像“!”这样的字符进入“%21”

components.path = [components.path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPathAllowedCharacterSet]];

//返回带“!”的 url,未编码

[items addObject:components.URL];

我在 components.path 中做错了什么吗?

提前感谢大家的帮助。

最佳答案

由于 URLPathAllowedCharacterSet 包含“!”,您需要通过创建 URLPathAllowedCharacterSet 的可变副本并删除“!”来创建新的字符集:

NSMutableCharacterSet *characterSet = [[NSCharacterSet URLPathAllowedCharacterSet] mutableCopy];
[characterSet removeCharactersInString:@"!"];

关于ios - URLPathAllowedCharacterSet 不编码感叹号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43401456/

相关文章:

javascript - 强制对 ajax 查询参数进行转义

android - 在 Android 中使用结构查询 (sq) 从 Google Spreadsheet API 检索数据时出错

android - Kotlin 多平台移动 : Flow<List<*SomeModel*>> gets mapped to Flow<NSArray> in iOS

ios - 带点击手势 Segue 的 UIView

ios - Branch.io 禁用 StatusBar 上的右箭头按钮 ("bnc.lt")

IOS:识别通用对象

iOS 在设置包中管理用户帐户

php - 无法在 iOS 中解析从 PHP 获取的 JSON

objective-c - 用于具有不同标题和值的弹出窗口的 Cocoa 库

mod-rewrite - 从 URL 中删除编码的问号