gpt4 book ai didi

ios - 构建 queryString 时 NSURLComponents 出现问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:58:15 24 4
gpt4 key购买 nike

我收到这个错误:

-[__NSCFNumber stringByAddingPercentEncodingWithAllowedCharacters:]: unrecognized selector sent to instance 0x7fab88c21750        

我用这段代码得到它:

+ (NSString *)queryStringFromDictionary:(NSDictionary *)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;
}

所以我不明白这个问题或我该如何解决它。有什么想法吗?

最佳答案

你正在传递一个包含 NSNumber 作为键或值的字典。 queryWithItem:value: 期望键和值都是字符串。

选项 1

解决此问题的最简单方法是将所有键/值视为 NSObject 并使用 stringWithFormat 将它们转换为字符串。

替换:

NSURLQueryItem *newQueryItem = [NSURLQueryItem queryItemWithName:key value:value];

与:

NSURLQueryItem *newQueryItem = [NSURLQueryItem queryItemWithName:[NSString stringWithFormat:@"%@", key] value:[NSString stringWithFormat:@"%@", value]];

选项 2

如果你想坚持所有键都是字符串,我建议你使用泛型来输入字典,如果找到非字符串键则使用 NSAssert(这样你就可以找到你当前的错误)。

+ (NSString *)queryStringFromDictionary:(NSDictionary <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 - 构建 queryString 时 NSURLComponents 出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35189517/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com