我收到此错误:
-[__NSCFNumber stringByAddingPercentEncodingWithAllowedCharacters:]: unrecognized selector sent to instance 0x7fab88c21750
我用这段代码得到它:
+ (NSString *)queryStringFromDictionaryNSDictionary *)queryDictionary
{
NSURLComponents *components = [NSURLComponents componentsWithString""];
NSMutableArray *urlQueryComponents = [NSMutableArray array];
for (NSString *key in [queryDictionary allKeys])
{
NSString *value = queryDictionary[key];
NSURLQueryItem *newQueryItem = [NSURLQueryItem queryItemWithName:key value:value];
[urlQueryComponents addObject:newQueryItem];
}
components.queryItems = urlQueryComponents; // HERE I GET THE ERROR
return [components query];
}
如果出现错误,我的 queryDictionary 如下所示:
{
lat = "49.3437442";
lng = "17.0571453";
username = demo;
}
当我的 queryDictionary 看起来像下面一样时,它工作正常!
{
latlng = "49.343744,17.057145";
sensor = true;
}
所以我无法理解这个问题或如何解决它。有什么想法吗?
Best Answer-推荐答案 strong>
您正在传递一个包含 NSNumber 作为键或值的字典。 queryWithItem:value: 期望键和值都是字符串。
选项 1
解决此问题的最简单方法是将所有键/值视为 NSObject,并使用 stringWithFormat 将它们转换为字符串。
替换:
与:
NSURLQueryItem *newQueryItem = [NSURLQueryItem queryItemWithName:[NSString stringWithFormat"%@", key] value:[NSString stringWithFormat"%@", value]];
选项 2
如果您想坚持所有键都是字符串,我建议您使用泛型作为输入字典,如果找到非字符串键则使用 NSAssert(这样您就可以找到当前的错误)。
+ (NSString *)queryStringFromDictionaryNSDictionary <NSString*, NSString*> *)queryDictionary {
NSURLComponents *components = [NSURLComponents componentsWithString""];
NSMutableArray *urlQueryComponents = [NSMutableArray array];
for (NSString *key in [queryDictionary allKeys]) {
NSString *value = queryDictionary[key];
// confirm key/value are strings
NSAssert([key isKindOfClass:[NSString class]], @"keys must be strings!");
NSAssert([value isKindOfClass:[NSString class]], @"values must be strings!");
NSURLQueryItem *newQueryItem = [NSURLQueryItem queryItemWithName:key value:value];
[urlQueryComponents addObject:newQueryItem];
}
components.queryItems = urlQueryComponents;
return [components query];
}
关于ios - 构建查询字符串时出现 NSURLComponents 问题,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/35189517/
|