//字典转链接(参数)
- (NSString *)keyValueStringWithDict:(NSDictionary *)dict
{
if (dict == nil) {
return nil;
}
NSMutableString *string = [NSMutableString stringWithString:@"?"];
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[string appendFormat:@"%@=%@&",key,obj];
}];
if ([string rangeOfString:@"&"].length) {
[string deleteCharactersInRange:NSMakeRange(string.length - 1, 1)];
}
return string;
}
//链接转字典 (参数)
-(NSDictionary *)dictionaryWithUrlString:(NSString *)urlStr
{
if (urlStr && urlStr.length && [urlStr rangeOfString:@"?"].length == 1) {
NSArray *array = [urlStr componentsSeparatedByString:@"?"];
if (array && array.count == 2) {
NSString *paramsStr = array[1];
if (paramsStr.length) {
NSMutableDictionary *paramsDict = [NSMutableDictionary dictionary];
NSArray *paramArray = [paramsStr componentsSeparatedByString:@"&"];
for (NSString *param in paramArray) {
if (param && param.length) {
NSArray *parArr = [param componentsSeparatedByString:@"="];
if (parArr.count == 2) {
[paramsDict setObject:parArr[1] forKey:parArr[0]];
}
}
}
return paramsDict;
}else{
return nil;
}
}else{
return nil;
}
}else{
return nil;
}
}
//特殊链接解析不了 。 'https://wwww.baidu.com/#/sdffff?name=sdfff&pass=dddff'
/**
获取url的所有参数
@param url 需要提取参数的url
@return NSDictionary
*/
-(NSDictionary *) parameterWithURL:(NSURL *) url {
NSMutableDictionary *parm = [[NSMutableDictionary alloc]init];
//传入url创建url组件类
NSURLComponents *urlComponents = [[NSURLComponents alloc] initWithString:url.absoluteString];
//回调遍历所有参数,添加入字典
[urlComponents.queryItems enumerateObjectsUsingBlock:^(NSURLQueryItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[parm setObject:obj.value forKey:obj.name];
}];
return parm;
}