-1

still learning programming and have a question.

im trying to download image from url and put it in cells, ive successfully done it with text but not with images.

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return posts.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCell(withIdentifier:"searchCell", for: indexPath)
    as! CustomTableViewCell
    cell.titleField?.text = posts[indexPath.row].caption
    cell.descriptionField?.text = posts[indexPath.row].description
    cell.tagsField?.text = posts[indexPath.row].tags
    let photoUrl = posts[indexPath.row].photoUrl
    cell.SearchImage.image = ...

//url is stored in photoUrl

    return cell
}

}

Alex. E
  • 69
  • 8

3 Answers3

0

I recommend you to use this third party library.

Kingfisher handles everything for you.

A lightweight, pure-Swift library for downloading and caching images from the web.

If you don't know how to install it, have a look at Cocoapods, it's pretty straightforward.

Anyway, here is the only line of code needed to set an image from your URL with Kingfisher :

cell.SearchImage.kf.setImage(with: photoUrl)

By the way, you should follow the Swift convention described here in order to make your code easier to read and "universal".

Have a look : Naming Convention

0

Use a pod to make it easy

use SDWebImage

then use it like this :

import SDWebImage

cell.SearchImage.sd_setImage(with: photoUrl, placeholderImage: nil)
  • Thank you, having problem with install, i followed the guide and all looked right but when i import webimage it says it doesnt exist.. even thought its in the podfile below. – Alex. E Mar 20 '18 at 18:13
0

On swift3 You can use Alamofire (https://cocoapods.org/) for that.

Step 1:

Integrate using pods.

pod 'Alamofire', '~> 4.7'

pod 'AlamofireImage', '~> 3.3'

Step 2:

import AlamofireImage

import Alamofire

Step 3:

Alamofire.request("https:// YOUR URL").responseImage { response in

if let image = response.result.value {
    print("image downloaded: \(image)")
self.myImageview.image = image
}
}

Or you can try this -

let url = URL(string: "https:// YOUR URL")

let task = URLSession.shared.dataTask(with: url!) { data, response, error in
    guard let data = data, error == nil else { return }

    DispatchQueue.main.async() 
    {    
        self.imageView.image = UIImage(data: data)
    }
}

task.resume()
Rashed
  • 2,349
  • 11
  • 26