从完成处理程序更改标签文本

时间:2015-02-17 20:12:37

标签: swift

我有一个带有按钮和标签的示例视图。 当用户按下按钮时,一个动作从外部站点接收一个json,我需要在标签上放一个字符串。

我尝试从完成处理程序执行此操作,但此时无法识别标签插座。

这是我的代码:

import UIKit

class ViewController: UIViewController, NSURLSessionDelegate {

    @IBOutlet weak var lblReceivedText: UILabel!

    var session : NSURLSession!


    required init(coder aDecoder: NSCoder)
    {
        super.init(coder: aDecoder)

        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        configuration.timeoutIntervalForRequest = 15.0

        session = NSURLSession(configuration : configuration, delegate : self, delegateQueue : nil )

    }


    override func viewDidLoad()
    {
        super.viewDidLoad()

    }


    @IBAction func btnGerarMensagem(sender: AnyObject)

    {

        var errorx : NSError?
        let url = NSURL( string: "http://labs.bible.org/api/?passage=random&type=json")

        let task = session.dataTaskWithURL(url! ,
            completionHandler: { [weak self] (data: NSData!,
                response : NSURLResponse! ,
                error : NSError! ) in

                var error: NSError?
                var array = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as NSArray
                var citacao: NSDictionary = array.objectAtIndex(0) as NSDictionary

                var Quote = citacao["text"] as String
                lblReceivedText.text = Quote                
                self!.session.finishTasksAndInvalidate()


        })

        task.resume()

    } // IBAction




}

1 个答案:

答案 0 :(得分:1)

编译器应该在您引用self属性时向您发出警告,告知您需要使用UILabel。试试这个:

let task = session.dataTaskWithURL(url! ,
    completionHandler: { [weak self] (data: NSData!,
        response : NSURLResponse! ,
        error : NSError! ) in

        var error: NSError?
        var array = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as NSArray
        var citacao: NSDictionary = array.objectAtIndex(0) as NSDictionary

        var Quote = citacao["text"] as String
        NSOperationQueue.mainQueue().addOperationWithBlock {
            self?.lblReceivedText.text = Quote
        }
})

注意:如果您在闭包中声明[weak self],请使用self?而不是self!展开。此时它们具有相同的效果,但如果在取消分配视图控制器后处理程序返回,则第二个会使应用程序崩溃。