gpt4 book ai didi

iphone - 如何从 URL 中捕获所需的值

转载 作者:行者123 更新时间:2023-11-29 13:41:57 25 4
gpt4 key购买 nike

我需要从字符串中提取变量的值,该字符串恰好是一个 URL。字符串/url 作为单独的 php 查询的一部分加载,而不是浏览器中的 url。

网址看起来像:

http://gmail.com?access_token=ab8w4azq2xv3dr4ab37vvzmh&token_type=bearer&expires_in=3600

如何获取 access_token 的值,在此示例中为 ab8w4azq2xv3dr4ab37vvzmh?

最佳答案

这段代码应该做到这一点:

- (NSString *)extractToken:(NSURL *)URL
{
NSString *urlString = [URL absoluteString];
NSRange start = [urlString rangeOfString:@"access_token="];
if (start.location != NSNotFound)
{
NSString *token = [urlString substringFromIndex:start.location+start.length];
NSRange end = [token rangeOfString:@"&"];
if (end.location != NSNotFound)
{
//trim off other parameters
token = [token substringToIndex:end.location];
}
return token;
}
//not found
return nil;
}

或者,这里有一个更通用的解决方案,它将所有查询参数提取到一个字典中:

- (NSDictionary *)URLQueryParameters:(NSURL *)URL
{
NSString *queryString = [URL query];
NSMutableDictionary *result = [NSMutableDictionary dictionary];
NSArray *parameters = [queryString componentsSeparatedByString:@"&"];
for (NSString *parameter in parameters)
{
NSArray *parts = [parameter componentsSeparatedByString:@"="];
NSString *key = [[parts objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
if ([parts count] > 1)
{
id value = [[parts objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[result setObject:value forKey:key];
}
}
return result;
}

关于iphone - 如何从 URL 中捕获所需的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8849873/

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