我有一个应用程序,它解析URL链接的JSON提要,然后将这些URL存储在字符串中。这工作正常,URL链接如下所示:
(
"http://instagram.com/p/cCEfu9hUxG/"
)
如何删除URL末尾的括号和撇号?
我需要在UIWebView中打开URL,但我不能,因为URL的末尾有括号和撇号。
来自JSON Feed的信息正在UITableView中显示。当用户点击UITableView的一个单元格时,单元格的相关URL将存储在NSString中,然后由我的UIWebView读取。这是我的代码:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
NSString *storyLink = [[[[_dataSource objectAtIndex: storyIndex] objectForKey:@"entities"] objectForKey:@"urls"] valueForKey:@"expanded_url"];
//[webviewer loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:storyLink]]];
NSLog(@"\n\n LINK: %@", storyLink);
[UIView beginAnimations:@"animateAdBannerOn" context:NULL];
[UIView setAnimationDuration:1.2];
webviewer.alpha = 1.0;
[UIView commitAnimations];
}
我故事是NSString中的URL。
以下是JSON Feed:
{
"coordinates": null,
"favorited": false,
"truncated": false,
"created_at": "Sat Aug 25 17:26:51 +0000 2012",
"id_str": "239413543487819778",
"entities": {
"urls": [
{
"expanded_url": "https://dev.twitter.com/issues/485",
"url": "https://t.co/p5bOzH0k",
"indices": [
97,
118
],
"display_url": "dev.twitter.com/issues/485"
}
],
"hashtags": [
],
"user_mentions": [
]
}
谢谢,Dan。
答案 0 :(得分:1)
您的NSLog
输出表明
NSString *storyLink = [[[[_dataSource objectAtIndex: storyIndex]
objectForKey:@"entities"]
objectForKey:@"urls"]
valueForKey:@"expanded_url"];
不会按预期返回NSString
,而是NSArray
。可能是那样的
JSON对象中"urls"
的值是字典数组而不是单个字典?在这种情况下,以下应该有效:
NSString *storyLink = [[[[[_dataSource objectAtIndex: storyIndex]
objectForKey:@"entities"]
objectForKey:@"urls"]
objectAtIndex:0]
objectForKey:@"expanded_url"];
如果显示JSON输出,则可能会有更具体的答案。
注:
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
可以简化为
int storyIndex = indexPath.row;
(见"NSIndexPath UIKit Additions"。)
更新:要进一步本地化您的问题,我建议您拆分
将代码编码到单独的命令中,并检查"urls"
数组是否为空:
NSDictionary *dict = [_dataSource objectAtIndex: storyIndex];
NSDictionary *entities = [dict objectForKey:@"entities"];
NSArray *urls = [entities objectForKey:@"urls"];
if ([urls count] > 0) {
NSDictionary *firstUrl = [urls objectAtIndex:0];
NSString *storyLink = [firstUrl objectForKey:@"expanded_url"];
NSLog(@"LINK: %@", storyLink);
} else {
NSLog(@"URLS is an empty array!!");
}
如果它仍然崩溃,请设置“所有Objective-C Exceptions上的断点”进行检查 它完全崩溃的地方。