【问题标题】:How to update JSON File from web server如何从 Web 服务器更新 JSON 文件
【发布时间】:2014-03-30 14:17:08
【问题描述】:

我在 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 文件吗?

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

请帮忙...

【问题讨论】:

    标签: ios json network-programming nsurlconnection nsurlsession


    【解决方案1】:

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

    • 您需要身份验证吗?
    • 是否需要在后台模式下加载 JSON?
    • 您的 JSON 是否很大,以至于将其加载到内存中对系统来说不是那么好?
    • 您是否需要取消正在运行的请求,因为它可能会停止或耗时过长?
    • 您是否需要同时并行加载多个请求?

    还有更多。

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

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

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

    您可以在此处找到更多信息: Using NSURL Connection

    此外,Cocoa 和 Cocoa Touch 在NSURLConnectionNSURLSession 中提供了更多先进技术来完成这项任务。您可以在官方文档URL Loading System Programming Guide阅读更多内容。

    这里有一个如何使用异步便利类方法的简短示例: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 方法将在主线程上执行。

    【讨论】:

    • 感谢您的回复.. 唯一需要的是,当用户触摸刷新按钮时,来自网络服务器的数据应将应用程序中的当前 json 文件替换为更新的文件,并且当应用程序打开它应该使用默认的本地 json 文件。请帮助我是 Xcode 的新手
    • @user2975817 1. 更新了答案以显示一种将 JSON 保存到文件的简单方法。您需要提供文件的路径。 2. 请参阅语句self.places = jsonObject; 这在main 线程上执行。在这里,您可以放置​​任何代码来更新您的程序中的 JSON 对象。请注意,它已经保存在文件中。
    • @user2975817 上面的代码 sn-p 可以直接放在您的按钮操作中,该操作在视图控制器中实现。在这种情况下,self 将引用视图控制器。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-26
    • 2015-06-04
    • 1970-01-01
    相关资源
    最近更新 更多