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

前端 未结 8 1696
猫巷女王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:37

    Just a friendly post for those who don't want to write boilerplate code while building NSURL with NSURLComponents.
    Since iOS8 we have NSURLQueryItem that helps building URL request freaking fast.

    I wrote a little handy category to ease the work, that you can grab here: URLQueryBuilder
    Here is example of how easy it is to work with it:

    NSString *baseURL = @"https://google.com/search";
    NSDictionary *items = @{
        @"q"  : @"arsenkin.com",
        @"hl" : @"en_US",
        @"lr" : @"lang_en"
    };
    
    NSURL *URL = [NSURL ars_queryWithString:baseURL queryElements:items];  
    // https://google.com/search?q=arsenkin.com&hl=en_US&lr=lang_en
    

提交回复
热议问题