2015-10-18 87 views
0

我想從api web服務異步加載圖像到iOS 9的swift中的uitableview。下面是我的播放列表控制器的代碼。提前致謝。Swift將字符串轉換爲UIIMAGE

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() 
} 
+0

的NSData(contentsOfURL:URL,選項:[])它不是異步的。你應該使用NSURLSession的dataTaskWithURL –

回答

1

使用NSURLSession dataTaskWithURL用於異步任務:

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) 
      } 
    } 
} 

tableView.reloadData()應該在主線程中執行(因爲NSURLSession dataTaskWithUrl結果是在後臺線程)

dispatch_async(dispatch_get_main_queue(), { 
    tableView.reloadData() 
})