Objective-C: How to add query parameter to NSURL?

前端 未结 8 1686
猫巷女王i
猫巷女王i 2020-12-23 18:45

Let\'s say I have an NSURL? Whether or not it already has an empty query string, how do I add one or more parameters to the query of the NSUR

相关标签:
8条回答
  • The answers above mentioned the NSURLComponents,it's a good class to handle URL.

    My answer is as follows:

    Create a category with NSURL,like NSURL+Additions.h. Then,add the following method and implement it.

    - (NSURL *)URLByAppendingQueryParameters:(NSDictionary *)queryParameters
    {
        if (queryParameters.count == 0) {
            return self;
        }
    
        NSArray *queryKeys = [queryParameters allKeys];
        NSURLComponents *components = [[NSURLComponents alloc] initWithURL:self resolvingAgainstBaseURL:NO];
        NSMutableArray * newQueryItems = [NSMutableArray arrayWithCapacity:1];
    
        for (NSURLQueryItem * item in components.queryItems) {
            if (![queryKeys containsObject:item.name]) {
                [newQueryItems addObject:item];
            }
        }
    
        for (NSString *key in queryKeys) {
            NSURLQueryItem * newQueryItem = [[NSURLQueryItem alloc] initWithName:key value:queryParameters[key]];
            [newQueryItems addObject:newQueryItem];
        }
    
        [components setQueryItems:newQueryItems];
    
        return [components URL];
    }
    
    0 讨论(0)
  • 2020-12-23 19:48

    I have an extension to NSURLComponents that add query item, in swift:

    extension NSURLComponents {
    
        func appendQueryItem(name name: String, value: String) {
            var queryItems: [NSURLQueryItem] = self.queryItems ?? [NSURLQueryItem]()
            queryItems.append(NSURLQueryItem(name: name, value: value))
            self.queryItems = queryItems
        }
    
    }
    

    To use,

    let components = NSURLComponents(string: urlString)!
    components.appendQueryItem(name: "key", value: "value")
    
    0 讨论(0)
提交回复
热议问题