简体   繁体   English

快速下载URL并填充uiimageview

[英]swift downloading url and populating uiimageview

I'm having difficulty getting each image of my tableviewcell to show the thumbnail of my blog. 我很难获取tableviewcell的每个图像来显示博客的缩略图。 the link is valid as i had it print to screen to make sure it works here is the block of code causing my brain aneurysm 该链接有效,因为我已将其打印到屏幕上以确保其在此处有效,这是导致我的脑动脉瘤的代码块

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) 

    let blogPost: BlogPost = blogPosts[indexPath.row]
    //cell.textLabel?.text = blogPost.postTitle
    postImageLink = blogPost.postImageLink
    cell.textLabel?.text = blogPost.postImageLink

    if postImageLink != "" && cell.imageView?.image != nil {
        dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {

            cell.imageView?.image =  UIImage(data: NSData(contentsOfURL: NSURL(string:self.postImageLink)!)!)
        }
    } else {
            cell.imageView?.image = UIImage(named: "IMG_0079")
        }



    return cell
}

i set the text label to postimagelink only to ensure it was parsing the correct code for future usage. 我将文本标签设置为postimagelink只是为了确保它正在解析正确的代码以备将来使用。 To be clear the problem is the thumbnails of my blog won't load. 要明确的问题是我的博客的缩略图无法加载。 Only the preset image incase a thumbnail isn't present..postImageLink is a unique url for each thumbnail that I parsed. 如果没有缩略图,则只有预设图像。.postImageLink是我解析的每个缩略图的唯一URL。 (yeah i know i can write a parser but can't solve this problem =(..) any help is appreciated before I throw my laptop off the roof thanks! here is image (是的,我知道我可以写一个分析器,但解决不了这个问题=(..)之前,我把我的笔记本电脑顶盖关闭感谢任何帮助表示赞赏! 这里是图像

-rookieprogrammer -菜鸟程序员

try to make two blocks instead, to retrieve and set the image 尝试制作两个块,以检索和设置图像

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {

    // retrieve image from url
    let image = UIImage(data: NSData(contentsOfURL: NSURL(string:self.postImageLink)!)!)

    dispatch_async(dispatch_get_main_queue(), { Void in
        // set image in main thread
        cell.imageView?.image =  image
    })

}

can read more here 在这里可以阅读更多

Your code is working. 您的代码正在运行。 It's just that should be doing it in the main_queue, UI main thread, to edit any UI objects. 只是应该在UI主线程main_queue中执行此操作,以编辑任何UI对象。

dispatch_async(dispatch_get_main_queue()) {
      () -> Void in
  // retrieve image from url
  let image = UIImage(data: NSData(contentsOfURL:NSURL(string:self.postImageLink)!)!)

  cell.imageView?.image =  image
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM