2016-07-29 61 views
1
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) 
     } 
    } 
} 

}; 

昨天我有應用程序運行,今天早上我剛剛得到新的錯誤消息,甚至不允許編譯代碼。他們說'缺少'Default[email protected]「啓動圖像」和「命令/應用程序/ Xcode.app /內容/開發者/工具鏈/ XcodeDefault.xctoolchain/usr/bin/swiftcode」。提前致謝。Xcode Swift 2天氣應用程序問題

+0

命令/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc失敗,退出代碼爲1 –

+0

嘗試清理項目。另外,你檢查這個鏈接 - http://stackoverflow.com/questions/30848208/new-warnings-in-ios-9 –

回答

0

你需要的東西添加到您的Info.plist文件:

enter image description here

這是因爲你想從中獲取數據的URL鏈接不是一個安全的鏈接,所以加入這個給你info.plist允許您訪問該鏈接。只要去找你info.plist並右鍵點擊並選擇添加行,然後添加你在上面的圖片中看到的。

此外,從viewDidLoad方法中刪除getWeatherData函數,因爲您不需要,因爲您按下按鈕時調用它。

此外,我注意到您的setLabels函數中沒有正確設置您的某個標籤,因爲它們都嘗試設置cityTempLabel標籤,因此請將另一個標籤更新爲cityNameLabel

建立和運行,它應該都工作。