iOS: parse a URL into segments

前端 未结 4 457
闹比i
闹比i 2020-12-02 08:41

What\'s an efficient way to take an NSURL object such as the following:

foo://name/12345 

and break it up into one string and one unsigned

4条回答
  •  爱一瞬间的悲伤
    2020-12-02 09:30

    Actually there is a better way to parse NSURL. Use NSURLComponents. Here is a simle example:

    Swift:

    extension URL {
        var params: [String: String]? {
            if let urlComponents = URLComponents(url: self, resolvingAgainstBaseURL: true) {
                if let queryItems = urlComponents.queryItems {
                    var params = [String: String]()
                    queryItems.forEach{
                        params[$0.name] = $0.value
                    }
                    return params
                }
            }
            return nil
        }
    }
    

    Objective-C:

    NSURLComponents *components = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
        NSArray *queryItems = [components queryItems];
    
        NSMutableDictionary *dict = [NSMutableDictionary new];
    
        for (NSURLQueryItem *item in queryItems)
        {
            [dict setObject:[item value] forKey:[item name]];
        }
    

提交回复
热议问题