首页 iOS 如何优雅的获取 URL 中的参数
文章
取消

iOS 如何优雅的获取 URL 中的参数

如果给你一个 URL, 你会如何提取 URL 中所附带的参数?

一般做法

一般来说, 大多数人可能会使用这种方法, 逐层分解获取想要的结果.

1
2
3
4
5
6
7
8
NSString *URL = @"https://www.zhk1024.com?p=1&t=1563368296&token=94a08da1fecbb6e8b46990538c7b50b2";
NSString *query = [URL componentsSeparatedByString:@"?"].lastObject;
NSArray *params = [query componentsSeparatedByString:@"&"];
NSMutableDictionary *kvs = [NSMutableDictionary new];
for (NSString *param in params) {
    NSArray *sup = [param componentsSeparatedByString:@"="];
    [kvs setValue:sup.lastObject forKey:sup.firstObject];
}

优雅的做法

第一种做法也没错, 但是却略为繁琐, 并且分割过成功还要做多层判断来保证代码的健壮性. 幸好 iOS 为我们提供了一个专门处理 URL 的一个类 NSURLComponents.

使用 NSURLComponents 来获取参数.

OC代码
1
2
3
4
5
6
NSString *URL = @"https://www.zhk1024.com?p=1&t=1563368296&token=94a08da1fecbb6e8b46990538c7b50b2";
NSURLComponents *components = [[NSURLComponents alloc] initWithString:URL];
NSMutableDictionary *kvs = [NSMutableDictionary new];
for (NSURLQueryItem *item in components.queryItems) {
    [kvs setValue:item.value forKey:item.name];
}
Swift 代码
1
2
3
4
5
6
let URL = "https://www.zhk1024.com?p=1&t=1563368296&token=94a08da1fecbb6e8b46990538c7b50b2"
let components = URLComponents(string: URL)
var kvs : [String: Any] = [:];
components?.queryItems?.forEach({ (item) in
    kvs[item.name] = item.value
})

输出结果为:

1
2
3
4
5
{
    p = 1;
    t = 1563368296;
    token = 94a08da1fecbb6e8b46990538c7b50b2;
}
本文由作者按照 CC BY 4.0 进行授权