gpt4 book ai didi

ios - 一种在 Objective C 中解析 URL 字符串的干净而健壮的方法

转载 作者:行者123 更新时间:2023-11-29 01:04:33 26 4
gpt4 key购买 nike

我需要获取一个字符串,该字符串表示可以采用多种格式的 URL 并对其进行标准化,以使其符合 URL 规范。

如果 URL 字符串没有方案,或者它的方案不是 'http' 或 'https',则应使用默认方案。

我想使用 NSURLComponents,但如果没有提供方案,它会将主机解析为路径

NSURLComponents *components = [NSURLComponents componentsWithString:@"www.google.com.au"];
components.scheme = @"http";
NSLog(@"1: %@", components.path);
NSLog(@"2: %@", components.host);
NSLog(@"3: %@", components.string);

testtest[2619:869020] 1: www.google.com.au
testtest[2619:869020] 2: ((null))
testtest[2619:869020] 3: http:www.google.com.au <-- Invalid

因此我在 NSString 上得到了这个类别

#define DEFAULT_SCHEME @"http"

@implementation NSString (standardiseUrlFormat)

- (NSString*)standardiseUrlFormat {
NSURLComponents *components = [NSURLComponents componentsWithString:self];
BOOL hasScheme = components.scheme != nil;

// If no scheme or an invalid scheme is provided, default to http
if (!hasScheme) {
// We have to use string concatenation here because NSURLComponents will
// put the hostname as the path if there is no scheme
return [NSString stringWithFormat:@"%@://%@", DEFAULT_SCHEME, self];
}

// Now we know that a scheme exists, check if it is a correct scheme
if (![components.scheme isEqualToString:@"http"] &&
![components.scheme isEqualToString:@"https"]) {
// Overwrite scheme if not supported
components.scheme = DEFAULT_SCHEME;
}

return [components string];
}

@end

输出如下

NSLog(@"1: %@", [@"http://www.google.com" standardiseUrlFormat]);
NSLog(@"2: %@", [@"www.google.com" standardiseUrlFormat]);
NSLog(@"3: %@", [@"https://www.google.com" standardiseUrlFormat]);
NSLog(@"4: %@", [@"https://www.google.com/some_path" standardiseUrlFormat]);
NSLog(@"5: %@", [@"www.google.com/some_path" standardiseUrlFormat]);

testtest[7411:944022] 1: http://www.google.com
testtest[7411:944022] 2: http://www.google.com
testtest[7411:944022] 3: https://www.google.com
testtest[7411:944022] 4: https://www.google.com/some_path
testtest[7411:944022] 5: http://www.google.com/some_path

谁能提出一个不使用两种方法(NSURLComponents 和字符串连接)来构造字符串的更简洁的解决方案?

最佳答案

根本不要使用字符串连接。使用 NSURLComponents 来形成所需的 NSURL;这就是它的用途。例如,如果您不喜欢 scheme 是什么, scheme 设置为您想要的。

编辑 我想我在想,如果检测到这是一个无主机 URL,您可以手动重新调整它,例如

let s = "www.apple.com/whatever" as NSString
let arr = s.pathComponents
let c = NSURLComponents()
c.scheme = "http"
c.host = arr[0]
c.path = "/" + (Array(arr.dropFirst()) as NSArray).componentsJoinedByString("/")

但这也许无法做到,问题实际上是没有方案的 URL 或多或少不是 URL。

关于ios - 一种在 Objective C 中解析 URL 字符串的干净而健壮的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36561763/

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