ios - 函数类型作为参数类型,如何更改此函数中的 UI 元素值?

标签 ios json xcode swift asynchronous

我从 json 异步获取数据并想要更改 UILabel 文本,但文本没有 canhge。 我认为这不起作用,因为函数 changeLabel(...) 运行 inside func getJsonArray(...),但为什么以及如何这样做正确

class DetailViewController: UIViewController {

@IBOutlet weak var detailDescriptionLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    //load data from website, and run function changeLabel for change text on UI
    getJsonArray("www.domen.com/app.php?action=get_data", doItFunc: changeLabel)
}

更改 UILabel 文本的函数

func changeLabel(jsonArray: NSArray){
    //self.detailDescriptionLabel.text = "workplease"
    self.detailDescriptionLabel.text = jsonArray[0]["newText"] as! String

    println(self.detailDescriptionLabel.text)
    //print in console new Data, but UILabel text in simulator(and phone) not change

}

从网络获取数据并异步运行用户函数的函数

func getJsonArray(uri: String, doItFunc: (NSArray)->Void){

    if let url = NSURL(string: uri) {
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in
            if error != nil {
                println("error: \(error.localizedDescription): \(error.userInfo)")
            }else if data != nil {
                if let sJson = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as? Dictionary<String, AnyObject> {

                    let results: NSArray = sJson[jsonKey] as! NSArray

如果获取到数据,则运行用户函数 doItFunc(results)

                    doItFunc(results)

                }else{
                    if let str = NSString(data: data, encoding: NSUTF8StringEncoding) {
                        println("Received data:\n\(str)")
                    }else {
                        println("unable to convert data to text")
                    }
                }
            }
        })
        task.resume()
    }
    else {
        println("Unable to create NSURL")
    }
}
}

最佳答案

解析 JSON 的数据任务回调位于后台线程上。您无法在后台线程上更新 UI。分派(dispatch)到主线程:

dispatch_async(dispatch_get_main_queue()) {
    doItFunc(results)
}

关于ios - 函数类型作为参数类型,如何更改此函数中的 UI 元素值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31340825/

相关文章:

iphone - UIWebView 未加载

json - 使用 Delphi 2012 反序列化嵌套的 json 对象

swift - MapBox IOS SDK swift : how to show the user annotations from specific zoomLevel without delete and add again?

objective-c - "Unlock to delete"编辑 subview

ios - 在 GPUImage2 中尝试 shiTomasiFeatureDetector 过滤器时 EXC_BAD_ACCESS

PHP 函数在本地主机上运行,​​但不在我的服务器上运行

javascript - 带有 json 正文的 POST 请求 javascript

iphone - 在 Xcode 数据模型发生任何更改后,我不断收到 "save operation failure"

xcode - 无法在库/开发者/XCPGDevices 上创 build 备集

ios - 如何解决xcode 5 中的apple LLVM 5.0 错误?