10

提取和删除方案名称的正确方法是://什么NSURL

例如:

 note://Hello  ->  @"Hello"
 calc://3+4/5  ->  @"3+4/5"

所以

NSString *scheme = @"note://";
NSString *path   = @"Hello";

供以后使用:

[[NSNotificationCenter defaultCenter] postNotificationName:scheme object:path];
4

5 回答 5

17

你可以这样看(大部分是未经测试的代码,但你明白了)

- (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;
}
于 2013-06-14T04:49:35.960 回答
6

我的倾向是滚动您自己的字符串搜索:

NSRange dividerRange = [urlString rangeOfString:@"://"];
NSUInteger divide = NSMaxRange(dividerRange);
NSString *scheme = [urlString substringToIndex:divide];
NSString *path = [urlString substringFromIndex:divide];

这完全符合您的要求,将 URL 围绕其方案分成两半。对于更高级的处理,您必须提供更多详细信息。

于 2013-07-23T22:17:07.413 回答
5

只需使用名为 NSURL 的 API:resourceSpecifier:)

并从字符串的开头删除两个斜杠:

NSURL *url = [NSURL URLWithString:@"https://some.url.com/path];

url.resourceSpecifier将导致://some.url.com/path

于 2018-07-05T09:50:30.493 回答
1

请记住,不要与框架对抗,尤其是在涉及 NSURL 时。这个 SO 答案很好地分解了它的能力。https://stackoverflow.com/a/3693009/142358

NSURL 的方案路径属性正是你想要的(假设你的 URL 的其余部分看起来像一个路径)给你留下了这个:

NSString *schemeWithDelimiter = [NSString stringWithFormat:@"%@://",[myURL scheme]];
[[NSNotificationCenter defaultCenter] postNotificationName: schemeWithDelimiter object:[myURL path];

无需字符串搜索!

于 2015-04-13T03:27:20.917 回答
1

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]
    }
}
于 2020-01-26T19:08:38.520 回答