【问题标题】:Can't get the latest value from JSON in Xcode无法从 Xcode 中的 JSON 获取最新值
【发布时间】:2017-06-02 02:30:23
【问题描述】:

我想从 Xcode (Objective-C) 中的 JSON 获取值。 但是,如果我更改值并再次构建应用程序,则值不会更改。

我尝试的是

  1. 将值设置为“1”并构建应用程序(第一次) -> 我可以得到“1”。

  2. 将值从“1”设置为“0”并构建应用程序(第二次) -> 我仍然可以得到“1”。

  3. 从 iPhone 中删除应用程序一次,然后重新构建应用程序 -> 我可以得到“0”。

为什么我无法从 JSON 中获取最新值?

代码:

-(int)getJsonValue{

    Reachability* curReach = [Reachability reachabilityForInternetConnection];
    NetworkStatus netStatus = [curReach currentReachabilityStatus];

    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

    if (netStatus == NotReachable) {
        // Disconnect
        _jsonValue = 0;

    } else {
        // Connect (Always through here)

        NSURL* url = [NSURL URLWithString:pathReview];
        NSURLSessionConfiguration* config = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession* session = [NSURLSession sessionWithConfiguration:config];

        NSURLSessionDataTask* task =
        [session dataTaskWithURL:url
               completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

                   id jsonData = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

                   if ([jsonData isKindOfClass:[NSArray class]]){
                       NSMutableArray *objects = [NSMutableArray array];
                       objects = jsonData;

                       _jsonValue = [[objects objectAtIndex:0] intValue];


                   }

                   dispatch_semaphore_signal(semaphore);

               }];
        [task resume];

        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

    }

    return _jsonValue;
}

【问题讨论】:

  • 您将要提取的文件托管在哪里?您是在更新文件然后立即尝试该应用程序吗?这可能是您托管文件的服务器的问题,因为您没有在您期望的时候实际提供更新的文件。我已经看到了在 Amazon S3 上托管东西的类似问题,它可以在实际提供新文件之前保留缓存文件一段时间
  • 我用 Coda 更改了值,并立即和 24 小时后检查了设备上的值。但仍然没有改变。在另一个应用程序上,我可以立即获取最新值。
  • 在方法内使用块时无法返回值。你需要用块声明方法。

标签: ios objective-c json xcode


【解决方案1】:

你需要通过块返回值,因为你在函数中使用了块。

-(void)getJsonValueWithCallback:(void(^)(NSInteger jsonValue ))callback{
    if (netStatus == NotReachable) {
        callback(0);
    }
    else{
        callback(1);
    }
}

通话

[self getJsonValueWithCallback:^(NSInteger jsonValue) {
        NSLog(@"%ld",(long)jsonValue);
        //
    }];

【讨论】:

    猜你喜欢
    • 2013-03-02
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    • 2013-11-27
    • 2016-02-23
    • 2021-11-04
    • 2020-05-31
    • 2021-11-26
    相关资源
    最近更新 更多