2017-05-05 51 views
0

數據我試圖讓有關從黑暗的天空API每小時的天氣信息,但代碼停止工作的,如果讓數據=每小時[「數據」]作爲? [字符串:AnyObject]行(每行後檢查打印的東西)。我想知道我的代碼有什麼問題。我認爲這可能與「數據」有關,但我不確定。無法從黑暗的天空API

let Task2 = URLSession.shared.dataTask(with: urlRequestDark) { (data, response, error) in 
     if error == nil { 
      do { 
       let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject] 

       if let hourly = json["hourly"] as? [String : AnyObject] { 
        if let data = hourly["data"] as? [String : AnyObject]{ 


         if let hourNum = data["14"] as? [String : AnyObject] { 
          if let chanceRain = hourNum["precipProbability"] as? Float{ 
           self.chanceHour1 = String(chanceRain) 
          } 
          DispatchQueue.main.sync { 
           self.ChanceRainLabel.text = self.chanceHour1 
          } 
         } 
        } 

       } 

      } catch let jsonError { 
       print(jsonError.localizedDescription) 
      } 
     } 
    } 
    Task2.resume() test 

奇怪的部份是,這樣做的工作:

let urlRequestDark = URLRequest(url: URL (string: "https://api.darksky.net/forecast/(API Key)/(coordinates)")!) 

    let Task = URLSession.shared.dataTask(with: urlRequestDark) { (data, response, error) in 
     if error == nil { 
      do{ 
       let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject] 


       if let currently = json["currently"] as? [String : AnyObject] { 

        if let chance2 = currently["precipProbability"] as? Float{ 
         print(String(chance2)) 
         self.chance = String(Int(chance2 * 100)) + "%" 
         self.PreType = currently["precipType"] as? String 
        } 

         if let _ = json["error"]{ 
        } 

        DispatchQueue.main.sync{ 
         self.TypeLabel.text = self.PreType 
         self.ChanceLabel.text = self.chance 
        } 
       } 


      }catch let jsonError{ 
       print(jsonError.localizedDescription) 
      } 
     } 
    } 
    Task.resume() 
+0

@Check您請求的URL我認爲你是用URL –

+0

我使用相同的URLRequest兩個例子 –

回答

1

你犯了幾個錯誤。

首先,"data"是字典的陣列,所以應該投給[[字符串:AnyObject]。

其次,你試圖通過字符串,而不是詮釋到數組下標。

第三,使用self逃脫封閉潛在創建保留週期。

讓我向您推薦一些固定和調整的代碼。

let task2 = URLSession.shared.dataTask(with: urlRequestDark) { [weak self] (data, response, error) in 
    guard error == nil else { return } 
    do { 
     if let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String : AnyObject], 
      let hourly = json["hourly"] as? [String : AnyObject], 
      let data = hourly["data"] as? [[String : AnyObject]], 
      data.count > 14, 
      let chanceRain = data[14]["precipProbability"] as? Float { 
       self?.chanceHour1 = String(chanceRain) 
       DispatchQueue.main.sync { 
        self?.ChanceRainLabel.text = self?.chanceHour1 
       } 
     } 
    } catch let jsonError { 
     print(jsonError.localizedDescription) 
    } 
} 
task2.resume() 
+0

我想讓你知道,我愛你失蹤了!有用! –

0

嘗試這樣

import UIKit 

class WebService: NSObject { 

    var session = URLSession() 

    public class var sharedInstance: WebService { 
     struct Singleton { 
      static let instance = WebService() 
     } 
     return Singleton.instance 
    } 

    override init() { 
     let configuration = URLSessionConfiguration.default 
     configuration.timeoutIntervalForRequest = 30.0 
     configuration.timeoutIntervalForResource = 60.0 
     session = URLSession(configuration: configuration) 

    } 


public func weatherData(coordinate:String,APIkey:String,completion:@escaping (_ responsedata:NSDictionary?,_ error:NSError?) -> Void) { 

      var Baseurl = "https://api.darksky.net/forecast/\(APIkey)/\(coordinate)" 
      Baseurl = Baseurl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! 
      let weatherRequestUrl = URL(string: Baseurl) 
      let request = NSMutableURLRequest(url: weatherRequestUrl!) 
      let task = session.dataTask(with: request as URLRequest) { (data, response, error) in 

       guard error == nil && data != nil else { 

        return 
       } 
       if let httpStatus = response as? HTTPURLResponse{ 
        if httpStatus.statusCode != 200 { 

         print("Something is wrong") 
        } 
       } 
       do { 
        let WindlocationData = try JSONSerialization.jsonObject(with: data! as Data, options:.allowFragments) as! NSDictionary 

        print(WindlocationData) 
        completion(WindlocationData,nil) 
       } 
       catch let error as NSError { 

        completion(nil,error) 
       } 
      } 
      task.resume() 

     } 
} 

並調用API這個樣子!

FUNC callAPI(經緯度:字符串,APIkeyParm:字符串){

WebService.sharedInstance.weatherData(coordinate: latlong,APIkey: APIkeyParm) { (responsData, error) in 

    if error == nil{ 

     print("Response data is-\(responsData)") 
    } 
} 

}

調用,比如你需要通過經緯度這樣

let latlongStr = "\(latitude),\(longitude)" 
self.callAPI(latlong: latlongStr,APIkeyParm: "APIKeyString") 

一importent件事方法這種格式23.022504999999999,72.571362100000002