1

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...

CouchDeveloper
  • 18,174
  • 3
  • 45
  • 67
Manish Malviya
  • 87
  • 3
  • 10

1 Answers1

0

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.

Community
  • 1
  • 1
CouchDeveloper
  • 18,174
  • 3
  • 45
  • 67
  • Thank you for your reply.. The only thing required is that when user touches the refresh button the data from the web server should replace the present json file in the app with the updated one and when the app is opened it should use the default local json file. Please help I am new to Xcode – Manish Malviya Feb 27 '14 at 09:52
  • @user2975817 1. Updated the answer to show a simple way to safe the JSON to a file. You nee to provide the path to the file. 2. Please see statement `self.places = jsonObject;` this executes on the _main_ thread. Here you would place whatever code to update your JSON object in your program. Notice, that it is already saved in the file. – CouchDeveloper Feb 27 '14 at 10:04
  • @user2975817 The code snippet above can be placed directly in your button action which is implemented in a View Controller. In this case, `self` will refer to the View Controller. – CouchDeveloper Feb 27 '14 at 10:23