我已经尝试了很多方法,但是这个小小的字符串无法进行URL解码。
NSString *decoded;
NSString *encoded = @"fields=ID%2CdeviceToken";
decoded = (__bridge NSString*)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (CFStringRef)encoded, NULL, NSUTF8StringEncoding);
NSLog(@"decodedString %@", decoded);
上面的代码只是在替换百分比转义后记录相同的(!)字符串。
那里有可靠的解决方案吗?我认为基于某些文档的某种RegEx解决方案可行。有什么建议吗?
答案 0 :(得分:32)
另一种选择是:
NSString *decoded = [encoded stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
答案 1 :(得分:17)
使用CFSTR("")
代替NULL
作为倒数第二个参数。来自CFURL reference:
charactersToLeaveEscaped
百分比转义序列的字符,例如空格字符的%20,要保持原样。传递NULL以指定不替换百分比转义,或者指定空字符串(CFSTR(“”))以指定全部替换。
NSString *encoded = @"fields=ID%2CdeviceToken";
NSString *decoded = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (CFStringRef)encoded, CFSTR(""), kCFStringEncodingUTF8);
NSLog(@"decodedString %@", decoded);
打印:
2013-03-26 21:48:52.559 URLDecoding [28794:303] decodingString fields = ID,deviceToken
答案 2 :(得分:1)
Swift 3
import Foundation
let charSet = CharacterSet.urlPathAllowed.union(.urlQueryAllowed) // just use what you need, either path or query
let enc = "Test Test Test".addingPercentEncoding(withAllowedCharacters: charSet)!
let dec = enc.removingPercentEncoding!
print("Encoded: \(enc)")
print("Decoded: \(dec)")
输出:
编码:测试%20测试%20测试
解码:测试测试