我正在尝试从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
}
答案 0 :(得分: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
}