美文网首页
iOS URL地址解析

iOS URL地址解析

作者: 邓布利多教授 | 来源:发表于2019-08-27 17:30 被阅读0次

需求是:解析一段URL地址,获取它的各个部分的内容

  • 直接上代码

  • .h文件

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface URLAnalysisTools : NSObject

+(NSDictionary *)urlWithString:(NSString *)url;

@end

NS_ASSUME_NONNULL_END
  • .m文件
#import "URLAnalysisTools.h"

@implementation URLAnalysisTools

/**
 
 @property (nullable, readonly, copy) NSString *absoluteString;
 @property (readonly, copy) NSString *relativeString;
 @property (nullable, readonly, copy) NSURL *baseURL;
 @property (nullable, readonly, copy) NSURL *absoluteURL;
 @property (nullable, readonly, copy) NSString *scheme;
 @property (nullable, readonly, copy) NSString *resourceSpecifier;
 @property (nullable, readonly, copy) NSString *host;
 @property (nullable, readonly, copy) NSNumber *port;
 @property (nullable, readonly, copy) NSString *user;
 @property (nullable, readonly, copy) NSString *password;
 @property (nullable, readonly, copy) NSString *path;
 @property (nullable, readonly, copy) NSString *fragment;
 @property (nullable, readonly, copy) NSString *parameterString;
 @property (nullable, readonly, copy) NSString *query;
 @property (nullable, readonly, copy) NSString *relativePath;

 */
+(NSDictionary *)urlWithString:(NSString *)url{
    
    NSURL *urlBase = [NSURL URLWithString:url];
    
    //1.先按照‘&’拆分字符串
    NSArray *array = [urlBase.query componentsSeparatedByString:@"&"];
    //2.初始化两个可变数组
    NSMutableArray *mutArrayKey = [[NSMutableArray alloc]init];
    NSMutableArray *mutArrayValue = [[NSMutableArray alloc]init];
    //3.以拆分的数组内容个数为准继续拆分数组,并将拆分的元素分别存到两个可变数组中
    for (int i=0; i<[array count]; i++) {
        NSArray *arr = [array[i] componentsSeparatedByString:@"="];
        [mutArrayKey addObject:arr[0]];
        [mutArrayValue addObject:arr[1]];
    }
    //4.初始化一个可变字典,并设置键值对
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjects:mutArrayValue forKeys:mutArrayKey];
    
    return @{@"scheme":urlBase.scheme?:@"",
             @"host":urlBase.host?:@"",
             @"port":urlBase.port?:@"",
             @"path":urlBase.path?:@"",
             @"query":dict};
    
}

@end

这个小工具可以直接把一段地址的各个部分解析出来,并返回一个字典。例如:https://www.baidu.com/s?rsv_idx=1&wd=%E4%B8%AD%E5%8D%8E%E4%BA%BA%E6%B0%91%E5%85%B1%E5%92%8C%E5%9B%BD%E9%A3%9F%E5%93%81%E5%AE%89%E5%85%A8%E6%B3%95&usm=2&ie=utf-8&rsv_cq=&rsv_dl=0_right_recommends_merge_21102&euri=6c07e88eed77425a8d4fb75d8db41ead
包括它的参数部分也会解析成一个字典一同返回,打印结果如下:

打印结果.png

全剧终

相关文章

网友评论

      本文标题:iOS URL地址解析

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