我从Google Calendar Free / Busy API中提取数据。我在POST响应中获得的JSON数据被编码为NSData,转换为String但我看不到完整的响应。我无法将NSData转换为可以看到Google的整个响应的格式。
这是Google的预期回复:
{
"kind": "calendar#freeBusy",
"timeMin": "2016-10-17T17:40:00.000Z",
"timeMax": "2016-10-17T17:45:00.000Z",
"calendars": {
"ID_REDACTED@resource.calendar.google.com": {
"busy": [
{
"start": "2016-10-17T17:40:00Z",
"end": "2016-10-17T17:45:00Z"
}
]
}
}
}
但我只能在回复中看到这么多数据:
responseString = {
"kind": "calendar#freeBusy",
"timeMin": "2016-10-17T17:40:00.000Z",
"timeMax": "2016-10-17T17:45:00.000Z"
}
我无法弄清楚如何在日历之后公开JSON响应的最后部分:'
这是我的代码:
func fetchEvents() {
for (calID,_) in dict {
let request = NSMutableURLRequest(URL: NSURL(string: "https://www.googleapis.com/calendar/v3/freeBusy?access_token=\(GIDSignIn.sharedInstance().currentUser.authentication.accessToken)")!)
request.HTTPMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let jsonObject: [String:AnyObject] = [
"timeMin" : "2016-10-17T10:40:00-07:00",
"timeMax" : "2016-10-17T10:45:00-07:00",
"items" : [
"id" : "\(calID)"
],
]
do {
let data1 = try NSJSONSerialization.dataWithJSONObject(jsonObject, options: NSJSONWritingOptions.PrettyPrinted)
let convertedString = String(data: data1, encoding: NSUTF8StringEncoding)
json = convertedString!
} catch let myJSONError {
print(myJSONError)
}
request.HTTPBody = json.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else {
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response!)")
}
let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString!)")
}
task.resume()
}
}
我已经尝试过NSJSONSerialization.dataWithJSONdata而没有运气。我认为因为NSData在这里被转换为String:
let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
它没有显示完整的JSON响应。我觉得数据需要被转换为[String:AnyObject],但我并不是100%肯定。
感谢您的帮助!
答案 0 :(得分:2)
let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
不对响应应用任何魔法,它只是将服务器发送的字节转换为字符。如果你没有看到你期望看到的东西,那是因为服务器没有发送它。