2017-05-05 44 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