【问题标题】:XCode iphone programming: sending a URL string parsed from an xml file via segue to be loaded in UIImageViewXCode iphone编程:通过segue发送从xml文件解析的URL字符串以加载到UIImageView中
【发布时间】:2013-07-04 20:33:19
【问题描述】:

我正在创建一个 iphone 应用程序,其中 2 个 URL 从 xml 文件传递​​并通过要加载到 UIImageView 中的 segue 从 UITableView 发送到详细视图。 这是我的 prepareForSegue 方法:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"detail"]) {
         NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
         NSMutableString *imgURL1 = [feeds[indexPath.row] objectForKey: @"imageURL1"];
         [[segue destinationViewController] setImg1:imgURL1];
         //img1 is declared in the detailviewcontroller class
    }
}

这是我在 detailViewController 中的 viewDidLoad:

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSURL * imageURL1 = [NSURL URLWithString:self.img1];
    NSData * imageData1 = [NSData dataWithContentsOfURL:imageURL1];
    UIImage * imag1e = [UIImage imageWithData:imageData1];
    appImage1.image = imag1e;
    //appImage1 is also declared in the detailViewController class
}

现在的问题是,当我运行应用程序时,appImage1 中没有显示任何内容,也没有报告错误或错误。 感谢您的帮助

【问题讨论】:

  • appImage1 是从情节提要中设置的吗?真的设置了吗?此外,在主线程上使用 dataWithContentsOfURL 也不是一个好主意。
  • 是的,它是从情节提要中设置的
  • 然后您进行了调试以检查 feeds 是否确实包含您认为的内容以及您认为的内容?

标签: objective-c xcode uiimageview nsxmlparser segue


【解决方案1】:

这里有几个问题:

1) 为什么是可变字符串? NSString 就够了。

2) 依赖“选定行”并不是很安全。这只是选择一行的副作用。理想情况下,您应该使用发件人。

NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell*)sender]; 

3) 不要在主线程上调用 URL 加载。相反,使用带有NSURLRequestNSURLConnection 的异步加载。在didFinishLoading回调中设置图片。

4) 检查还有什么问题:

  • 图像视图为零。
  • 字符串为零。
  • URL 为 nil 或无效。
  • 服务器没有响应或没有发送数据或时间过长。

【讨论】:

  • 你能给我一个关于如何在我的情况下使用异步加载的例子吗?
  • 当然。在this 问题的答案中查看我的代码。
【解决方案2】:

我解决了这个问题。 显然,问题出在 URL 上。 xml 解析器将 url 存储在 url 变量中,开头有一个空格,所以我所要做的就是使用 stringByTrimmingCharactersInSet 所以 segue 方法看起来像这样:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{

//sends the image link
    NSString *imageURLS = [feeds[indexPath.row] objectForKey: @"appImageURL"];
    imageURLS = [imageURLS stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSURL *img = [NSURL URLWithString: imageURLS];
    [[segue destinationViewController] setAppImageURL:img];
}

【讨论】:

  • 您应该接受我的回答,因为它包含了这个可能的错误,它显然对您有所帮助。欢迎使用 StackOverflow!
  • 您尚未接受答案。您必须单击我的答案投票数下方的复选标记。欢迎使用 StackOverflow!
猜你喜欢
  • 2011-01-31
  • 2012-12-07
  • 2013-06-26
  • 2016-04-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-10
  • 1970-01-01
相关资源
最近更新 更多