Xcode Swift 2天气App问题

时间:2016-07-29 07:53:04

标签: ios xcode api swift2 xcode7

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var cityNameTextField: UITextField!

@IBOutlet weak var cityNameLabel: UILabel!

@IBOutlet weak var cityTempLabel: UILabel!

@IBAction func getDataButtonClicked(sender: AnyObject) {

    getWeatherData("http://api.openweathermap.org/data/2.5/weather?q=\(cityNameTextField.text)&APPID=6de03a1d1554874e7594a89fad719dd0")
}


override func viewDidLoad() {
    super.viewDidLoad()
    getWeatherData("http://api.openweathermap.org/data/2.5/weather?q=London&APPID=6de03a1d1554874e7594a89fad719dd0")
    // Do any additional setup after loading the view, typically from a nib.    
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.        
}

func getWeatherData(urlString: String) {
    let url = NSURL(string: urlString)

    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
        dispatch_async(dispatch_get_main_queue(), {
            self.setLabels(data!)
        })   
    }
    task.resume()        
}


 var jsonData: AnyObject?

func setLabels(weatherData: NSData) {


    do {

        self.jsonData = try NSJSONSerialization.JSONObjectWithData(weatherData, options: []) as! NSDictionary

    } catch {
        //error handle here

    }

    if let name = jsonData!["name"] as? String {

        cityTempLabel.text = "\(name)"

    }



    if let main = jsonData!["main"] as? NSDictionary {
        if let temp = main["temp"] as? Double {
            cityTempLabel.text = String(format: "%.1f", temp)
        }
    }
}

};

昨天我运行了应用程序,今天早上我刚刚收到新的错误消息,甚至不允许编译代码。他们说' Missing" Default-568h@2x.png"发布图片'和' Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftcode'。提前谢谢。

1 个答案:

答案 0 :(得分:0)

您需要在info.plist文件中添加一些内容:

enter image description here

这是因为您尝试从中获取数据的网址链接不是安全链接,因此将此info.plist添加到您可以访问该链接。只需转到info.plist并右键单击并选择添加行,然后准确添加您在上图中看到的内容。

另外,从getWeatherData方法移除viewDidLoad功能,因为您不需要它,因为您按下按钮时会调用它。

此外,我发现您的setLabels功能中没有正确设置您的某个标签,因为它们都试图设置cityTempLabel标签,因此请更新另一个标签成为cityNameLabel

构建并运行它应该都可以工作。