从函数更改标签中的文本

时间:2015-03-02 15:29:37

标签: json swift uiviewcontroller uilabel ios8.1

我有一个从JSON通信请求数据的函数。

let title:NSString = jsonData.objectForKey("title") as NSString

现在我有一个带标题的变量。我想现在将它设置为我在视图上的标签。

这与我的文档

相关联
@IBOutlet weak var titleLabel: UILabel!

所以我认为最后一步应该是:

self.titleLabel.text = "\(title)"

可悲的是,这不起作用,我收到以下错误:

fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb) 

Thread 1: EXC_BAD_INSTRUCTION(code=EXC_i386_INVOP, subcode=0x0

我使用NSlog输出以检查变量title是否为nil,并且我发现它已填充:

[3426:83507] Using email accounts over POP on Windows 8.1 

任何帮助,因为我坚持这一点。

import Foundation

导入UIKit

class SolutionViewController: UIViewController {


@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var searchTerm: UITextField!

@IBAction func searchTapped(){

    var searchTerms:NSString = searchTerm.text

    if ( searchTerms.isEqualToString("") ) {

        var alertView:UIAlertView = UIAlertView()
        alertView.title = "Empty Search Term"
        alertView.message = "Please enter a search term"
        alertView.delegate = self
        alertView.addButtonWithTitle("OK")
        alertView.show()
    } else {
        let strSearchTerm:String = "\(searchTerms)"
        var convSearchTerm:String = strSearchTerm.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.LiteralSearch, range: nil)

        var post:NSString = "searchTerm=\(convSearchTerm)"

        NSLog("PostData: %@",post);

        var url:NSURL = NSURL(string: "http://turbo-tires-21-188007.euw1.nitrousbox.com/iosSearch.php?searchTerm=\(convSearchTerm)")!

        var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!

        var postLength:NSString = String( postData.length )

        var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"
        request.HTTPBody = postData
        request.setValue(postLength, forHTTPHeaderField: "Content-Length")
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")


        var reponseError: NSError?
        var response: NSURLResponse?

        var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)

        if ( urlData != nil ) {
            let res = response as NSHTTPURLResponse!;

            NSLog("Response code: %ld", res.statusCode);

            if (res.statusCode >= 200 && res.statusCode < 300)
            {
                var responseData:NSString  = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!

                NSLog("Response ==> %@", responseData);

                var error: NSError?

                let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary


                let title:NSString? = jsonData.objectForKey("title") as? NSString

                NSLog("\(title)")
                if title != "" {

                self.titleLabel.text = "\(title)"
                //[jsonData[@"success"] integerValue];
                }


            }
        }
    }
};
}

1 个答案:

答案 0 :(得分:0)

尝试通过执行以下操作将标题变量声明为可选:

var title:NSString? = jsonData.objectForKey("title") as? NSString

如果标签上显示nil,则键标题的对象不存在或者无法转换为NSString。执行此操作后,如果再次发生错误,则意味着您的titleLabel为nil并且是时候在故事板的连接检查器中检查标签的引用插座(如果存在)enter image description here