本文介绍了如何从Web服务器更新JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的本​​地数据保存在json文件中,例如:

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
    }
  ]
}

每当触摸刷新按钮时,我想更新Web服务器上的json文件吗?

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

总体思路是从服务器刷新本地数据并在没有Internet连接的情况下使用它

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

请帮助...

推荐答案

最合适的解决方案取决于您的确切要求.例如:

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

  • 您需要身份验证吗?
  • 是否需要在后台模式下加载JSON?
  • 您的JSON是否很大,因此将其加载到内存中对系统而言不是那么好吗?
  • 您是否需要取消正在运行的请求,因为它可能会停滞或花费太长时间?
  • 您是否需要同时加载多个请求?

还有一些.

如果您可以使用否回答所有要求,那么最简单的方法就足够了:

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

您可以在异步版本中使用NSURLConnection的便捷类方法

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

您可以在此处找到更多信息:使用NSURL连接

You can find more info here:Using NSURL Connection

此外,可可粉和可可粉在NSURLConnectionNSURLSession中提供了更多先进技术来完成此任务.您可以在官方文档 URL加载系统编程指南中阅读更多内容. .

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.

这里有一个简短的示例,介绍了如何使用异步便利类方法:sendAsynchronousRequest:queue:completionHandler::

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!
    }
}];

另请参见: [ NSData] writeToURL:options:error

handleError:应按以下方式实现:

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

例如,这确保在显示UIAlertView时,将在主线程上执行UIKit方法.

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

这篇关于如何从Web服务器更新JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 12:53