将NSString中的URL提取到NSMutableString中

时间:2016-08-11 20:48:24

标签: ios objective-c xcode

我有一个包含以下内容的文件:

cool name http://myurl1.tld/subdir/dir/var/ awesome\nanother cool name http://sub.domain.tld/dir/ nice\nsome nice name http://myname.tld/var/folder/ some\n 

我用这个Objetive-C代码读取文件:

NSData* data = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"../files/name.ext"]];
NSString* raw = [[NSString alloc]
                 initWithBytes:[data bytes]
                 length:[data length]
                 encoding:NSUTF8StringEncoding];

要从以上示例中提取所有网址,我使用:

NSDataDetector* detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray* matches = [detector matchesInString:raw options:0 range:NSMakeRange(0, [raw length])];

我的目标是将所有提取的URL附加到一个单独的字符串中,并使用分号(文件中没有任何其他内容)将它们分开:

NSMutableString *allURLStrings = [NSMutableString string];
for (NSString *s in matches) {
    [allURLStrings appendString:s];
    [allURLStrings appendString:@";"];
 }

每当我尝试运行代码时,我都会得到以下输出:

  

以NSException(lldb)类型的未捕获异常终止

我尝试使用这样的循环,但是substringForCurrMatch只包含斜杠(/):

NSMutableString * allRepoString = [NSMutableString string];  
for (NSTextCheckingResult *s in matches) {
        NSString* substringForCurrMatch = [s.URL path];
        [allRepoString appendString:substringForCurrMatch];
        [allRepoString appendString:@";"];
    }

当我在循环中检查s时,它会向我显示正确的对象: contenct of s

有没有办法让这段代码有效?

编辑完成错误消息:

2016-08-11 23:00:19.272 AppName[34831:2892247] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[fetchurlsource allURLStrings]: unrecognized selector sent to instance 0x14c55ea00'
*** First throw call stack:
(0x181fa2db0 0x181607f80 0x181fa9c4c 0x181fa6bec 0x181ea4c5c 0x1000e8b6c 0x1000e8ee0 0x187100c40 0x187100844 0x18710759c 0x187104a88 0x18717afa4 0x1873a63ac 0x1873aa5f0 0x1873a7764 0x1839437ac 0x183943618 0x1839439c8 0x181f5909c 0x181f58b30 0x181f56830 0x181e80c50 0x18716f94c 0x18716a088 0x1000edb10 0x181a1e8b8)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

1 个答案:

答案 0 :(得分:2)

到目前为止,您发布的所有代码都不会导致您发布的例外情况。

但以下代码不正确:

NSMutableString * allRepoString = [NSMutableString string];  
for (NSTextCheckingResult *s in matches) {
    NSString* substringForCurrMatch = [s.URL path];
    [allRepoString appendString:substringForCurrMatch];
    [allRepoString appendString:@";"];
}

您不想在path上调用s.URL方法。要将完整的URL作为字符串获取,请使用absoluteString。这将为您提供URL作为字符串。 path只是为您提供了网址的路径部分。

NSMutableString * allRepoString = [NSMutableString string];  
for (NSTextCheckingResult *s in matches) {
    NSString* substringForCurrMatch = [s.URL absoluteString];
    [allRepoString appendString:substringForCurrMatch];
    [allRepoString appendString:@";"];
}