我们开发中经常会用到NSURL,有时候我们需要对一个url进行分析整理,当然是可以按照RFC 1808的定义去自己分析,但是苹果已经给我们提供了解析url的方法,就是iOS 7时添加的NSURLComponents。
初始化方法如下:
//
- (instancetype)init;
//
- (nullable instancetype)initWithURL:(NSURL *)url resolvingAgainstBaseURL:(BOOL)resolve;
//
+ (nullable instancetype)componentsWithURL:(NSURL *)url resolvingAgainstBaseURL:(BOOL)resolve;
//
- (nullable instancetype)initWithString:(NSString *)URLString;
//
+ (nullable instancetype)componentsWithString:(NSString *)URLString;
常用的属性如下:
@property (nullable, readonly, copy) NSURL *URL;
@property (nullable, readonly, copy) NSString *string NS_AVAILABLE(10_10, 8_0);
@property (nullable, copy) NSString *scheme; // Attempting to set the scheme with an invalid scheme string will cause an exception.
@property (nullable, copy) NSString *user;
@property (nullable, copy) NSString *password;
@property (nullable, copy) NSString *host;
@property (nullable, copy) NSNumber *port; // Attempting to set a negative port number will cause an exception.
@property (nullable, copy) NSString *path;
@property (nullable, copy) NSString *query;
@property (nullable, copy) NSString *fragment;
@property (nullable, copy) NSString *percentEncodedUser;
@property (nullable, copy) NSString *percentEncodedPassword;
@property (nullable, copy) NSString *percentEncodedHost;
@property (nullable, copy) NSString *percentEncodedPath;
@property (nullable, copy) NSString *percentEncodedQuery;
@property (nullable, copy) NSString *percentEncodedFragment;
@property (nullable, copy) NSArray<NSURLQueryItem *> *queryItems NS_AVAILABLE(10_10, 8_0);
比如http://help.baidu.com:80/question?prod_id=1#!/feedback,scheme就是http, host是help.baidu.com, port就是80, path就是/question, query就是prod_id=1, fragment = !/feedback。