0

I would like to load an image from an api web service asynchronously into a uitableview with swift for iOS 9. Below is the code from my Playlist controller. Thanks in advance.

import UIKit

class PlaylistViewController: UITableViewController {

var playlists = [[String: String]]()

override func viewDidLoad() {
    super.viewDidLoad()

    let urlString = "http://xxxxxxx.xxx/api/v1/players/1/playlists?api_key=xxxxxxxxxxxx"

    if let url = NSURL(string: urlString) {

        if let data = try? NSData(contentsOfURL: url, options: []) {
            let json = JSON(data: data)


            if json != nil {
                parseJSON(json)
            } else {
                showError()
            }
        } else {
            showError()
        }
    } else {
        showError()
    }
}

func showError() {
    let ac = UIAlertController(title: "Loading error", message: "There was a problem loading the feed; please check your connection and try again.", preferredStyle: .Alert)
    ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
    presentViewController(ac, animated: true, completion: nil)
}

func parseJSON(json: JSON) {
    for result in json["playlists"].arrayValue {
        let title = result["title"].stringValue
        let id = result["id"].stringValue
        let cover_url = result["cover_url"].stringValue
        let obj = ["title": title, "id": id, "cover_url" : cover_url]
        playlists.append(obj)
    }

    tableView.reloadData()
}
1
  • NSData(contentsOfURL: url, options: []) it is NOT asynchronously. you should use NSURLSession dataTaskWithURL Commented Oct 18, 2015 at 1:01

1 Answer 1

1

Use NSURLSession dataTaskWithURL for asynchronously task:

override func viewDidLoad() {
    super.viewDidLoad()

    let urlString = "http://xxxxxxx.xxx/api/v1/players/1/playlists?api_key=xxxxxxxxxxxx"

    if let url = NSURL(string: urlString) {

        let session = NSURLSession.sharedSession()
        var task = session.dataTaskWithURL(url) { (data, response, error) -> Void in

            if let err = error {
                showError(err)
            } else {
                let json = NSString(data: data, encoding: NSUTF8StringEncoding)
                // json is a String, you should handle this String as JSON
                parseJSON(json)
            }
    }
}

Your tableView.reloadData() should be executed in main thread (because the NSURLSession dataTaskWithUrl result is in background thread)

dispatch_async(dispatch_get_main_queue(), {
    tableView.reloadData()
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.