如何更新从Web服务器JSON文件(How to update JSON File from web

2019-10-19 10:26发布

我有喜欢JSON文件我的本地数据:

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

我想更新JSON文件是没有在Web服务器上,每当刷新按钮感动?

总的想法是从服务器刷新本地数据和使用它没有互联网连接

请帮忙...

Answer 1:

最合适的解决方案取决于您的具体要求。 例如:

  • 您是否需要身份验证?
  • 你需要加载在后台模式的JSON?
  • 是您的JSON巨大,使软件加载到内存不会是很好的系统吗?
  • 你需要取消运行的请求,因为有机会,这档或时间过长?
  • 你需要一次并行加载许多要求?

和几个。

如果你能回答与无所有要求,那么最简单的方法就足够了:

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

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

你可以在这里找到更多的信息: 使用NSURL连接

此外可可和可可触摸提供更进步的技术NSURLConnectionNSURLSession来完成这个任务。 你可以阅读更多的官方文档中的URL加载系统编程指南 。

这里一个简短的样本,你如何使用异步方便的类方法: 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:选项:错误

编辑:

handleError:须执行如下:

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

这保证,当显示例如UIAlertView中,您UIKit的方法将在主线程上执行。



文章来源: How to update JSON File from web server