Search code examples
iosjsonswiftwordpress

Different results by parsing JSON API to WIFI and 4G in SWIFT


I have a Wordpress JSON API that provides this JSON (it's the list of comments for a post):

comments JSON

The JSON data are OK, I really have three comments for this post. In the WordPress admin I checked, all these comments are approved.

I tried to read this JSON, to create a list of NSObject Comment(), to display them in a tableview.

I tested the code below:

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)")
    }
}

The results are strange:

  • in the simulator with WIFI on -> allComments data OK
  • with playground with WIFI on -> allComments data OK
  • on a device iPhone/iPad iOS 9.2 with WIFI on -> allComments data OK
  • on a device iPhone/iPad iOS 9.2 with WIFI OFF, in 4G -> the API sent only two comments ("test comment number 2" and "test comment number 3"). My code above doesn't retrieve the last comment "Toyota"

I have repeated the test procedure with different devices and networks. 3G/4G networks often misses the last comments. But works perfectly with WiFi.

Why?

EDIT

I improved my code, but it still does not work.

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
}

EDIT 2

HTTP response in WIFI:

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";
} })

HTTP response in 4G:

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";
} })

EDIT 3

It seems to be because of the cache and not a 4G issue. I tested my code in Playground (with WIFI network), and the last comments are missing too. I tried to add:

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.requestCachePolicy = .ReloadIgnoringLocalAndRemoteCacheData
let urlSession:NSURLSession = NSURLSession(configuration: configuration)

or:

let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()()
let urlSession:NSURLSession = NSURLSession(configuration: configuration)

Same result, in my web browser the JSON are OK, but not on the app. The data haven't been updated.


Solution

  • It was a cache server problems.

    EDIT

    I was using W3 Total Cache Plugin for my Wordpress. I had to remove it to avoid my issue. I don't find exactly why, but now it works correctly.