iOS获取/删除url中的参数

1.获取URL中的某个参数:

- (NSString *)getParameter:(NSString *)parameter urlStr:(NSString *)url {
    
    NSError *error;
    
    if (!url) {
        
        return@"";
        
    }
    
    NSString *regTags = [[NSString alloc] initWithFormat:@"(^|&|\\?)+%@=+([^&]*)(&|$)",parameter];
    
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regTags options:NSRegularExpressionCaseInsensitive error:&error];
    
    NSArray *matches = [regex matchesInString:url options:0 range:NSMakeRange(0, [url length])];
    
    for (NSTextCheckingResult *match in matches) {
        
        NSString *tagValue = [url substringWithRange:[match rangeAtIndex:2]]; //分组2所对应的串
        
        return tagValue;
        
    }
    
    return@"";
    
}

 

2.删除URL中的某个参数:

- (NSString *)deleteParameter:(NSString *)parameter WithOriginUrl:(NSString *)originUrl {

    NSString *finalStr = [NSString string];
    
    NSMutableString * mutStr = [NSMutableString stringWithString:originUrl];
    
    NSArray *strArray = [mutStr componentsSeparatedByString:parameter];
    
    NSMutableString *firstStr = [strArray objectAtIndex:0];
    
    NSMutableString *lastStr = [strArray lastObject];
    
    NSRange characterRange = [lastStr rangeOfString:@"&"];

    if (characterRange.location !=NSNotFound) {

        NSArray *lastArray = [lastStr componentsSeparatedByString:@"&"];
        
        NSMutableArray *mutArray = [NSMutableArray arrayWithArray:lastArray];
        
        [mutArray removeObjectAtIndex:0];
        
        NSString *modifiedStr = [mutArray componentsJoinedByString:@"&"];
        
        finalStr = [[strArray objectAtIndex:0]stringByAppendingString:modifiedStr];
        
    } else {
        
        //以'?'、'&'结尾
        finalStr = [firstStr substringToIndex:[firstStr length] -1];
        
    }

    return finalStr;
    
}

 

posted @ 2017-05-24 14:37  Gerry_hu  阅读(1788)  评论(0编辑  收藏  举报