我有一个提供此 JSON 的 Wordpress JSON API(它是帖子的评论列表):
JSON数据没问题,我真的有3条评论这个帖子。在我检查的 wordpress 管理员中,所有这些评论都已批准。
我试图读取这个 JSON,创建一个 NSObject Comment() 列表,并在表格 View 中显示它们。
我测试了下面的代码:
let commentURL:NSURL = NSURL(string: "http://mywebsite.com/wp_api/v1/posts/1855/comments")!
if let data:NSData = NSData(contentsOfURL: commentURL) {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! [String: AnyObject]
if let allComments = json["comments"] as? NSArray{
print(allComments)
}
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
}
结果很奇怪:
- 在模拟器中打开 WIFI -> allComments 数据正常
- 有带 WIFI 的 Playground -> allComments 数据正常
- 在开启 WIFI 的 iPhone/iPad iOS 9.2 设备上 -> allComments 数据正常
- 在 WIFI 关闭的 iPhone/iPad iOS 9.2 设备上,4G -> API 仅发送了 2 条评论(“测试评论编号 2”和“测试评论编号 3”)。我上面的代码没有检索到最后一条评论“Toyota”
我已经用不同的设备和网络重复了测试过程。 3G/4G 网络经常错过最后的评论。但与 WiFi 完美配合。
为什么?
编辑
我改进了我的代码,但它仍然不起作用。
func downloadCommentsFrom(post:Post, completion: ((comments: [Comment]?) -> Void)) {
guard
let url = NSURL(string: "http://mywebsite.com/wp_api/v1/posts/\(post.postId)/comments")
else {return}
let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) in
completion(comments: self.getCommentsFromJSONAPI(data:data!))
}
task.resume()
}
func getCommentsFromJSONAPI(data data:NSData) -> [Comment] {
var comments:[Comment]=[]
do {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
if let allComments = json["comments"] as? NSArray{
comments = allComments
print(allComments)
}
} catch let error as NSError {
print("Failed to load JSON COMMENTS: \(error.localizedDescription)")
}
return comments
}
编辑 2
WIFI 中的 HTTP 响应:
Optional(<NSHTTPURLResponse: 0x17db0a80> { URL: http://mywebsite.com/wp_api/v1/posts/1136/comments } { status code: 200, headers {
"Cache-Control" = "max-age=3600, public";
Connection = "Keep-Alive";
"Content-Encoding" = gzip;
"Content-Type" = "text/html";
Date = "Sun, 20 Dec 2015 09:42:39 GMT";
Etag = 4652938bddc2501278c4e584c4612de4;
Expires = "Sun, 20 Dec 2015 10:42:39 GMT";
"Keep-Alive" = "timeout=5, max=99";
"Last-Modified" = "Thu, 01 Jan 1970 00:00:00 GMT";
Pragma = public;
Server = Apache;
"Set-Cookie" = "300gp=R3395909593; path=/; expires=Sun, 20-Dec-2015 10:48:14 GMT";
"Transfer-Encoding" = Identity;
Vary = "Accept-Encoding,User-Agent";
"X-Powered-By" = "PHP/5.4.45";
} })
4G 中的 HTTP 响应:
Optional(<NSHTTPURLResponse: 0x16d0d4b0> { URL: http://cestunmac.com/wp_api/v1/posts/1136/comments } { status code: 200, headers {
Age = 208;
"Cache-Control" = "public, max-age=3600";
"Content-Encoding" = gzip;
"Content-Type" = "text/html";
Date = "Sun, 20 Dec 2015 09:40:00 GMT";
Etag = 4652938bddc2501278c4e584c4612de4;
Expires = "Sun, 20 Dec 2015 10:40:00 GMT";
"Last-Modified" = "Thu, 01 Jan 1970 00:00:00 GMT";
Pragma = public;
Server = Apache;
"Transfer-Encoding" = Identity;
Vary = "Accept-Encoding,User-Agent";
"X-Powered-By" = "PHP/5.4.45";
} })
编辑 3
这似乎是因为缓存而不是 4G 问题。我在 Playground(使用 WIFI 网络)中测试了我的代码,最后的注释也丢失了。 我尝试添加:
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.requestCachePolicy = .ReloadIgnoringLocalAndRemoteCacheData
let urlSession:NSURLSession = NSURLSession(configuration: configuration)
或:
let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()()
let urlSession:NSURLSession = NSURLSession(configuration: configuration)
同样的结果,在我的网络浏览器中 JSON 是正确的,但在应用程序中不是。数据尚未更新。
最佳答案
let session = NSURLSession.sharedSession().dataTaskWithURL(commentURL!) { data, response, error in
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
if let allComments = json["comments"] as? [NSDictionary] {
print(allComments)
}
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
}
session.resume()
关于ios - 在SWIFT中解析JSON API到WIFI和4G的不同结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34322002/