ios - Swift 将字符串转换为 UIIMAGE

标签 ios swift swift2

我想使用 iOS 9 的 swift 从 api Web 服务异步加载图像到 uitableview 中。下面是我的播放列表 Controller 的代码。提前致谢。

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

最佳答案

使用 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()
})

关于ios - Swift 将字符串转换为 UIIMAGE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33193126/

相关文章:

iphone - 缺少 WWW 文件夹 Cordova/PhoneGap iOS

swift - PSPDFKit-检测注释是否已更改

ios - didFailToRegisterForRemoteNotificationsWithError : user refused error?

objective-c - 从 TableViewController 到 NavController 中嵌入的第二个 TVC 的 performSegueWithIdentifier 不起作用

swift - OSX/Swift 获取最前面运行的应用程序

swift - XCode9.4.1 swift : Showing image instead of text on map annotations

ios - 从 HealthKit 获取昨天的步数

ios - 我想在应用程序每 10 次快速打开时显示一条警报

iOS + swift 2 : Dynamic height in UITableViewCell doesn't work with an empty view

ios - 具有自定义 HitTest 的 UIWebView 子类