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

前端 未结 8 1822
猫巷女王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条回答
  •  無奈伤痛
    2020-12-23 19:25

    The iOS8+ modern way

    adding (or replacing 'ref' value if exists) ref=impm to url which is on min60.com

    if ([[url host] hasSuffix:@"min60.com"]) {
    
        NSURLComponents *components = [[NSURLComponents alloc] initWithURL:url resolvingAgainstBaseURL:NO];
        NSURLQueryItem * newQueryItem = [[NSURLQueryItem alloc] initWithName:@"ref" value:@"impm"];
        NSMutableArray * newQueryItems = [NSMutableArray arrayWithCapacity:[components.queryItems count] + 1];
        for (NSURLQueryItem * qi in components.queryItems) {
            if (![qi.name isEqual:newQueryItem.name]) {
                [newQueryItems addObject:qi];
            }
        }
        [newQueryItems addObject:newQueryItem];
        [components setQueryItems:newQueryItems];
    
        url = [components URL];
    }
    

提交回复
热议问题