How to update JSON File from web server

2019-07-23 10:44发布

问题:

I have my local data in json file like :

 {
  "locations": [
    {
      "title": "The Pump Room",
      "place": "Bath",
      "latitude": 51.38131,
      "longitude": -2.35959,
      "information": "The Pump Room Restaurant in Bath is one of the city’s most elegant places to enjoy stylish, Modern-British cuisine.",
      "telephone": "+44 (0)1225 444477",
      "visited" : true
    },
    {
      "title": "The Eye",
      "place": "London",
      "latitude": 51.502866,
      "longitude": -0.119483,
      "information": "At 135m, the London Eye is the world’s largest cantilevered observation wheel. It was designed by Marks Barfield Architects and launched in 2000.",
      "telephone": "+44 (0)8717 813000",
      "visited" : false
    },
    {
      "title": "Chalice Well",
      "place": "Glastonbury",
      "latitude": 51.143669,
      "longitude": -2.706782,
      "information": "Chalice Well is one of Britain's most ancient wells, nestling in the Vale of Avalon between the famous Glastonbury Tor and Chalice Hill.",
      "telephone": "+44 (0)1458 831154",
      "visited" : true
    }
  ]
}

I want to update the json file which is there on the webserver whenever the refresh button touched?

The overall idea is to refresh the local data from server and use it without internet connectivity

Please Help...

回答1:

The most appropriate solution depends on your exact requirements. For example:

  • Do you need authentication?
  • Do you require to load the JSON in background mode?
  • Is your JSON huge, so that loading it into memory wouldn't be that nice to the system?
  • Do you need to cancel a running request, since there are chances that it stalls or takes too long?
  • Do you need to load many requests at once in parallel?

and a few more.

If you can answer all requirements with No, then the most simple approach will suffice:

You can use NSURLConnection's convenient class method in the asynchronous version

+ (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue *)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler

You can find more info here: Using NSURL Connection

Furthermore Cocoa and Cocoa Touch provides more advances techniques in NSURLConnection and NSURLSession to accomplish this task. You can read more in the official documentation URL Loading System Programming Guide.

Here a short sample how you can use the asynchronous convenience class method: sendAsynchronousRequest:queue:completionHandler::

// Create and setup the request
NSMutableURLRequest* urlRequest = [NSURLRequest requestWithURL:url];
[urlRequest setValue: @"application/json; charset=utf-8" forHTTPHeaderField:@"Accept"];

// let the handler execute on the background, create a NSOperation queue:
NSOperationQueue* queue = [[NSOperationQueue alloc] init];

[NSURLConnection sendAsynchronousRequest:urlRequest 
                                   queue:queue  
                       completionHandler:^(NSURLResponse* response, 
                                                  NSData* data, 
                                                 NSError* error)
{
    if (data) {        
        // check status code, and optionally MIME type
        if ( [(NSHTTPURLResponse*)(response) statusCode] == 200 /* OK */) {
            NSError* error;
            // here, you might want to save the JSON to a file, e.g.:
            // Notice: our JSON is in UTF-8, since we explicitly requested this 
            // in the request header:
            if (![data writeToFile:path_to_file options:0 error:&error]) {
                [self handleError:err];  // execute on main thread!
                return;
            }

            // then, process the JSON to get a JSON object:
            id jsonObject = [NSJSONSerialization JSONObjectWithData:data 
                                                            options:0 
                                                              error:&error];
            ... // additionally steps may follow
            if (jsonObject) {
                // now execute subsequent steps on the main queue:
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.places = jsonObject;
                });
            }
            else {
                [self handleError:err];  // execute on main thread!
            }                
        }
        else {
             // status code indicates error, or didn't receive type of data requested
             NSError* err = [NSError errorWithDomain:...];
             [self handleError:err];  // execute on main thread!
        }                     
    }
    else {
        // request failed - error contains info about the failure
        [self handleError:error]; // execute on main thread!
    }        
}];

See also: [NSData] writeToURL:options:error

Edit:

handleError: SHALL be implemented as follows:

- (void) handlerError:(NSError*)error 
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self doHandleError:error];
    });
}

This ensures, when you display a UIAlertView for example, that your UIKit methods will be executed on the main thread.