【发布时间】:2013-11-21 05:27:39
【问题描述】:
我正在尝试从 twitter 加载图片。如果我只在 json 结果中使用 URL 而没有编码,在 dataWithContentsOfURL 中,我得到 nil URL 参数。如果我对其进行编码,我会得到如下的
%0A%20%20%20%20%22http://example.com/example.jpg%22%0A.
我知道我可以使用rangeOfString: 或stringByReplacingOccurrencesOfString:,但我可以确定它总是一样吗,有没有其他方法来处理这个问题,为什么这发生在我的推特回复而不是我的 Instagram 回复?
我也试过
stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]
它什么也没做。
这是直接来自json的URL...
2013-11-08 22:09:31:812 JaVu[1839:1547] -[SingleEventTableViewController tableView:cellForRowAtIndexPath:] [Line 406] (
"http://pbs.twimg.com/media/BYWHiq1IYAAwSCR.jpg"
)
这是我的代码
if ([post valueForKeyPath:@"entities.media.media_url"]) {
NSString *twitterString = [[NSString stringWithFormat:@"%@", [post valueForKeyPath:@"entities.media.media_url"]]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
twitterString = [twitterString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@", twitterString);
if (twitterString != nil){
NSURL *twitterPhotoUrl = [NSURL URLWithString:twitterString];
NSLog(@"%@", twitterPhotoUrl);
dispatch_queue_t queue = kBgQueue;
dispatch_async(queue, ^{
NSError *error;
NSData* data = [NSData dataWithContentsOfURL:twitterPhotoUrl options:NSDataReadingUncached error:&error];
UIImage *image = [UIImage imageWithData:data];
dispatch_sync(dispatch_get_main_queue(), ^{
[streamPhotoArray replaceObjectAtIndex:indexPath.row withObject:image];
cell.instagramPhoto.image = image;
});
});
}
}
【问题讨论】:
-
您在大约 3 小时前提出了类似的问题,相同的 URL。
-
是的,它很相似,但它是一个不同的问题,因为现在我知道为什么 dataWithContentsOfURL 返回 nil。我的新问题是如何去掉多余的字符
-
你的问题很不清楚。您显示的日志输出似乎是一个数组,因为它在单独的行上有带括号的字符串。如果它已经是一个有效的 URL 字符串,则不需要对字符串进行编码,实际上这样做是错误的并且会破坏事情。我认为您误解了您的数据结构。
-
抱歉不清楚。我对此还是陌生的。但你是对的。出于某种原因,它是一个数组。添加 objectAtIndex:0 解决了这个问题。如果您想发布答案,我会接受它作为答案。虽然我仍然很好奇为什么它会是一个数组。谢谢
标签: ios objective-c utf-8 nsstring nsurl