2016-05-19 144 views
0

我想從fitbit服務器獲取JSON數據並打印出來。當我運行第一個函數時,我總是得到零。但是,當我運行第二個函數時,它會正確輸出數據。我猜這與iPhone從服務器獲取JSON所花費的時間有關,但對於如何解決這個問題我完全無能爲力。我的最終目標是返回數據,但我顯然不能從完成處理程序中完成。方法總是返回零

static func getFitbitData(resource: ResourcePath, date: Date) -> Int? { 
     var rawData: NSData? 
     let request = oauth.request(forURL: NSURL(string: "https://api.fitbit.com/1/user/-/\(resource.rawValue)/date/\(date.toString())/1d.json")!) 
     let task = oauth.session.dataTaskWithRequest(request) { data, response, error in 
      if error != nil { 
       print("[ERROR] An error occured during request: \(error)") 
      } 
      else { 
       print("[SUCCESS] Data retrieved successfully") 
       rawData = data! 
      } 
     } 
     task.resume() 
     return ParsingEngine.parseFitbitData(ResourcePath.calories, data: rawData!) 
    } 



static func getFitbitData(resource: ResourcePath, date: Date) -> Int? { 
     let request = oauth.request(forURL: NSURL(string: "https://api.fitbit.com/1/user/-/\(resource.rawValue)/date/\(date.toString())/1d.json")!) 
     let task = oauth.session.dataTaskWithRequest(request) { data, response, error in 
      if error != nil { 
       print("[ERROR] An error occured during request: \(error)") 
      } 
      else { 
       print("[SUCCESS] Data retrieved successfully") 
       print(ParsingEngine.parseFitbitData(ResourcePath.calories, data: data!)) 
      } 
     } 
     task.resume() 
     return nil 
    } 

回答

1

你說得對,函數返回之前你的數據從服務器填充。爲什麼你不能從完成處理程序中完成?這應該工作:

static func getFitbitData(resource: ResourcePath, date: Date, completion: (data: Int?) -> Void) { 
     var rawData: NSData? 
     let request = oauth.request(forURL: NSURL(string: "https://api.fitbit.com/1/user/-/\(resource.rawValue)/date/\(date.toString())/1d.json")!) 
     let task = oauth.session.dataTaskWithRequest(request) { data, response, error in 
      if error != nil { 
       print("[ERROR] An error occured during request: \(error)") 
      } 
      else { 
       print("[SUCCESS] Data retrieved successfully") 
       let endData = ParsingEngine.parseFitbitData(ResourcePath.calories, data: data!) 
       completion(endData) 
      } 
     } 
     task.resume() 
    } 

您可以致電此像這樣:

FitbitService.getFitbitData(myResource, date: myDate) { data in 
    //work with your data here 
}