首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Xcode Swift 2天气应用问题

Xcode Swift 2天气应用问题
EN

Stack Overflow用户
提问于 2016-07-29 15:53:04
回答 1查看 171关注 0票数 1
代码语言:javascript
复制
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)
        }
    }
}

};

昨天我运行了应用程序,今天早上我收到了新的错误消息,甚至不允许编译代码。他们说‘缺少’默认-568h@2x.png“启动图像‘和’命令/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftcode'.提前谢谢。

EN

回答 1

Stack Overflow用户

发布于 2016-07-30 22:39:05

您需要在info.plist文件中添加以下内容:

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

另外,从viewDidLoad方法中删除getWeatherData函数,因为您不需要该函数,因为您在按下按钮时会调用该函数。

另外,我注意到您的setLabels函数中有一个标签设置不正确,因为它们都试图设置cityTempLabel标签,因此请将另一个标签更新为cityNameLabel

构建并运行,它应该都能正常工作。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38653383

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档