【发布时间】:2016-04-12 00:51:06
【问题描述】:
我需要一个字符串来表示可以采用多种格式的 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 和字符串连接)来构造字符串的更简洁的解决方案?
【问题讨论】:
-
这太苛刻了。我怀疑将 mailto://example@example.com 更改为 example@example.com 是否有意义。或者 ftp,或者 file:// 或者基本上除了 http(s) 之外的任何东西。
-
没错,但在这种情况下,应该假设任何输入的 URL 字符串都应该具有 http 或 https 方案
-
那为什么不简单地做一个字符串替换操作呢?查找第一个“://”并将其前面的内容替换为 http(只要它不是 https)。如果没有找到,请在前面插入。
标签: ios objective-c cocoa-touch url