我有一个应用程序,它解析 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 提要:
{
"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": [
]
}
谢谢,丹。
最佳答案
您的 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 异常上的断点”来检查 它崩溃的确切位置。
关于ios - 在 iOS 中编辑 URL 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17774752/