4

我使用此函数从字符串中获取 URL,但我怎样才能将其取回?

- (NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding forString:(NSString *)string {
    string = (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge CFStringRef)string, NULL, (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ", CFStringConvertNSStringEncodingToEncoding(encoding));
    return string;
}
4

4 回答 4

15
[string stringByReplacingPercentEscapesUsingEncoding:NSUTF8Encoding];

顺便提一句。如果NSURL用于文件 url,请务必使用[url path]来获取未转义的路径字符串,而不是通过[url absoluteString].

于 2012-11-27T02:25:21.200 回答
7

采用

NSString *urlString = [url absoluteString];

以此目的。

于 2012-06-29T13:43:34.770 回答
0

使用此代码..

NSError* error = nil;
NSString* text = [NSString stringWithContentsOfURL:your_url encoding:NSASCIIStringEncoding error:&error];

这可能会帮助你

于 2012-06-29T13:59:02.807 回答
-1

我自己找到了答案:

- (NSString *)decodedURLString {
    NSString *string = (__bridge NSString*)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault,
                                                                                          (CFStringRef)self,
                                                                                          CFSTR(""),
                                                                                          CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));

    return string;
}

和编码:

- (NSString *)encodedURLString {
    NSString *string = (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                           (CFStringRef)self,
                                                                           NULL,
                                                                           CFSTR(":/=,!$&'()*+;[]@#?"),
                                                                           CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));

    return string;
}
于 2012-10-27T15:26:58.087 回答