美文网首页
iOS URL字符串常用处理方法

iOS URL字符串常用处理方法

作者: unspecx | 来源:发表于2019-02-13 14:36 被阅读0次

    https://github.com/Banzuofan/CommonKit/blob/master/CommonKit/Categories/NSString%2BURLHelper.h
    https://github.com/Banzuofan/CommonKit/blob/master/CommonKit/Categories/NSString%2BURLHelper.m

    ////    protocol :// hostname[:port] / path / [;parameters][?query]#fragment
    @interface NSString (URLHelper)
    - (NSArray<NSURLQueryItem *> *)parseURLQueryItems;
    - (NSDictionary<NSString *, NSString *> *)parseURLQueries;
    - (NSString *)stringByAppendingURLQueryItem:(NSURLQueryItem *)queryItem;
    - (NSString *)stringByAppendingURLQueryItemWithName:(NSString *)name value:(NSString *)value;
    - (NSString *)URLStringAddParamterWithName:(NSString *)name value:(NSString *)value;
    @end
    
    @implementation NSString (URLHelper)
    
    - (NSArray<NSURLQueryItem *> *)parseURLQueryItems
    {
        NSURLComponents *tmpURLComp = [NSURLComponents componentsWithString:self];
        if(!tmpURLComp){
            return nil;
        }
        return tmpURLComp.queryItems;
    }
    
    - (NSDictionary<NSString *, NSString *> *)parseURLQueries
    {
        NSArray<NSURLQueryItem *> *tmpURLQueryItems = [self parseURLQueryItems];
        if(tmpURLQueryItems){
            NSMutableDictionary *result = [NSMutableDictionary new];
            for(NSURLQueryItem *item in tmpURLQueryItems){
                if(item.value){
                  [result setObject:item.value forKey:item.name];
                }
            }
            return result;
        }
        return nil;
    }
    
    - (NSString *)stringByAppendingURLQueryItem:(NSURLQueryItem *)queryItem
    {
        NSURLComponents *tmpURLComp = [NSURLComponents componentsWithString:self];
        NSMutableArray<NSURLQueryItem *> *tmpURLQueryItems = tmpURLComp.queryItems.mutableCopy;
        NSURLQueryItem *exsitingItem = nil;
        for(NSURLQueryItem *item in tmpURLQueryItems){
            if([item.name isEqualToString:queryItem.name]){
                exsitingItem = item;
                break;
            }
        }
        if(exsitingItem){
            [tmpURLQueryItems removeObject:exsitingItem];
        }
        [tmpURLQueryItems addObject:queryItem];
        tmpURLComp.queryItems = tmpURLQueryItems;
        return tmpURLComp.string;
    }
    
    - (NSString *)stringByAppendingURLQueryItemWithName:(NSString *)name value:(NSString *)value
    {
        NSURLQueryItem *tmpQueryItem = [NSURLQueryItem queryItemWithName:name value:value];
        return [self stringByAppendingURLQueryItem:tmpQueryItem];
    }
    
    - (NSString *)URLStringAddParamterWithName:(NSString *)name value:(NSString *)value
    {
        return [self stringByAppendingURLQueryItemWithName:name value:value];
    }
    
    @end
    

    相关文章

      网友评论

          本文标题:iOS URL字符串常用处理方法

          本文链接:https://www.haomeiwen.com/subject/eycdeqtx.html