提取和删除方案名称的正确方法是://什么NSURL?
例如:
note://Hello -> @"Hello"
calc://3+4/5 -> @"3+4/5"
所以
NSString *scheme = @"note://";
NSString *path = @"Hello";
供以后使用:
[[NSNotificationCenter defaultCenter] postNotificationName:scheme object:path];
提取和删除方案名称的正确方法是://什么NSURL?
例如:
note://Hello -> @"Hello"
calc://3+4/5 -> @"3+4/5"
所以
NSString *scheme = @"note://";
NSString *path = @"Hello";
供以后使用:
[[NSNotificationCenter defaultCenter] postNotificationName:scheme object:path];
你可以这样看(大部分是未经测试的代码,但你明白了):
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
NSLog(@"url: %@", url);
NSLog(@"scheme: %@", [url scheme]);
NSLog(@"query: %@", [url query]);
NSLog(@"host: %@", [url host]);
NSLog(@"path: %@", [url path]);
NSDictionary * dict = [self parseQueryString:[url query]];
NSLog(@"query dict: %@", dict);
}
所以你可以这样做:
NSString * strNoURLScheme =
[strMyURLWithScheme stringByReplacingOccurrencesOfString:[url scheme] withString:@""];
NSLog(@"URL without scheme: %@", strNoURLScheme);
解析查询字符串
- (NSDictionary *)parseQueryString:(NSString *)query
{
NSMutableDictionary *dict = [[[NSMutableDictionary alloc] initWithCapacity:6] autorelease];
NSArray *pairs = [query componentsSeparatedByString:@"&"];
for (NSString *pair in pairs) {
NSArray *elements = [pair componentsSeparatedByString:@"="];
NSString *key = [[elements objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *val = [[elements objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[dict setObject:val forKey:key];
}
return dict;
}
我的倾向是滚动您自己的字符串搜索:
NSRange dividerRange = [urlString rangeOfString:@"://"];
NSUInteger divide = NSMaxRange(dividerRange);
NSString *scheme = [urlString substringToIndex:divide];
NSString *path = [urlString substringFromIndex:divide];
这完全符合您的要求,将 URL 围绕其方案分成两半。对于更高级的处理,您必须提供更多详细信息。
只需使用名为 NSURL 的 API:resourceSpecifier:)
并从字符串的开头删除两个斜杠:
NSURL *url = [NSURL URLWithString:@"https://some.url.com/path];
url.resourceSpecifier将导致://some.url.com/path
请记住,不要与框架对抗,尤其是在涉及 NSURL 时。这个 SO 答案很好地分解了它的能力。https://stackoverflow.com/a/3693009/142358
NSURL 的方案和路径属性正是你想要的(假设你的 URL 的其余部分看起来像一个路径)给你留下了这个:
NSString *schemeWithDelimiter = [NSString stringWithFormat:@"%@://",[myURL scheme]];
[[NSNotificationCenter defaultCenter] postNotificationName: schemeWithDelimiter object:[myURL path];
无需字符串搜索!
Swift5,网址扩展:
var resourceSpecifier: String {
get {
let nrl : NSURL = self as NSURL
return nrl.resourceSpecifier ?? self.absoluteString
}
}
var simpleSpecifier: String {
get {
let str = self.resourceSpecifier
return str[2..<str.count]
}
}