以下Swift代码必须运行两次才能在标签中显示JSON数据。在第一次运行时,标签只是保持空白。在我看来,问题可能是代码的JSON部分最后一行,但我无法弄清楚原因。我已经包含了以下代码。我还是个菜鸟,所以请保持温柔:D
class ViewController: UIViewController {
@IBOutlet weak var labelDegrees: UILabel!
@IBOutlet weak var labelSpeed: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Set logo in nav bar
navigationItem.titleView = UIImageView(image: UIImage(named: "logo"))
// Global save values
var appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
var context: NSManagedObjectContext = appDel.managedObjectContext!
// JSON Fetching
let urlPath = "http://api.openweathermap.org/data/2.5/weather?lat=55.564120&lon=12.568605"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
if (error != nil) {
println(error)
}
else {
// Delete old entries in CoreData
var request = NSFetchRequest(entityName: "WindData")
request.returnsObjectsAsFaults = false
var results = context.executeFetchRequest(request, error: nil)
for result in results! {
context.deleteObject(result as NSManagedObject)
context.save(nil)
}
// Start fetching JSON
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
var item = jsonResult["wind"] as NSDictionary
var degrees:Float = item["deg"] as Float
var speed:Float = item["speed"] as Float
// Start saving JSON
var newItem = NSEntityDescription.insertNewObjectForEntityForName("WindData", inManagedObjectContext: context) as NSManagedObject
var speedValue:Float = speed as Float
var degreesValue:Float = degrees as Float
newItem.setValue(speedValue, forKey: "speed")
newItem.setValue(degreesValue, forKey: "degrees")
context.save(nil)
}
})
task.resume()
// Start fetching from CoreData
var request = NSFetchRequest(entityName: "WindData")
request.returnsObjectsAsFaults = false
var results = context.executeFetchRequest(request, error: nil)
if results!.count > 0 {
for result in results as [NSManagedObject] {
let degrees:Float = result.valueForKey("degrees")! as Float
let speed:Float = result.valueForKey("speed")! as Float
if speed > 6.0 {
self.labelDegrees.text = "Go kitesurf: \(speed) m/s"
}
else {
self.labelDegrees.text = "Stay in: \(speed) m/s"
}
}
}
else {
println("No data")
}
}
答案 0 :(得分:0)
您实际上正在使用dataTaskWithURL
在另一个线程上获取数据。因此您需要在// Start fetching from CoreData
中编写dataTaskWithURL
代码。由于dataTaskWithURL
不会立即执行// Start fetching from CoreData
所以{{ 1 {}代码将在dataTaskWithURL
获取数据时首先被调用。所以请在下面补充代码
class ViewController: UIViewController {
@IBOutlet weak var labelDegrees: UILabel!
@IBOutlet weak var labelSpeed: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Set logo in nav bar
navigationItem.titleView = UIImageView(image: UIImage(named: "logo"))
// Global save values
var appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
var context: NSManagedObjectContext = appDel.managedObjectContext!
// JSON Fetching
let urlPath = "http://api.openweathermap.org/data/2.5/weather?lat=55.564120&lon=12.568605"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
dispatch_async(dispatch_get_main_queue(),{
if (error != nil) {
println(error)
}
else {
// Delete old entries in CoreData
var request = NSFetchRequest(entityName: "WindData")
request.returnsObjectsAsFaults = false
var results = context.executeFetchRequest(request, error: nil)
for result in results! {
context.deleteObject(result as NSManagedObject)
context.save(nil)
}
// Start fetching JSON
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
var item = jsonResult["wind"] as NSDictionary
var degrees:Float = item["deg"] as Float
var speed:Float = item["speed"] as Float
// Start saving JSON
var newItem = NSEntityDescription.insertNewObjectForEntityForName("WindData", inManagedObjectContext: context) as NSManagedObject
var speedValue:Float = speed as Float
var degreesValue:Float = degrees as Float
newItem.setValue(speedValue, forKey: "speed")
newItem.setValue(degreesValue, forKey: "degrees")
context.save(nil)
}
// Start fetching from CoreData
var request = NSFetchRequest(entityName: "WindData")
request.returnsObjectsAsFaults = false
var results = context.executeFetchRequest(request, error: nil)
if results!.count > 0 {
for result in results as [NSManagedObject] {
let degrees:Float = result.valueForKey("degrees")! as Float
let speed:Float = result.valueForKey("speed")! as Float
if speed > 6.0 {
self.labelDegrees.text = "Go kitesurf: \(speed) m/s"
}
else {
self.labelDegrees.text = "Stay in: \(speed) m/s"
}
}
}
else {
println("No data")
}
});
})
task.resume()
}