如何异步加载 JSON (iOS)

2023-12-31

我的应用程序使用 JSON 解析来自 Rails 应用程序的信息。我正在寻找一种异步加载 JSON 的方法,但由于代码的复杂性,我无法让我的代码与我找到的示例一起使用。我需要做什么才能异步加载 JSON?谢谢。

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSURL *upcomingReleaseURL = [NSURL URLWithString:@"http://obscure-lake-7450.herokuapp.com/upcoming.json"];

    NSData *jsonData = [NSData dataWithContentsOfURL:upcomingReleaseURL];

    NSError *error = nil;

    NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];

    NSArray *upcomingReleasesArray = [dataDictionary objectForKey:@"upcoming_releases"];

    //This is the dateFormatter we'll need to parse the release dates
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
    NSTimeZone *est = [NSTimeZone timeZoneWithAbbreviation:@"EST"];
    [dateFormatter setTimeZone:est];
    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]]; //A bit of an overkill to avoid bugs on different locales

    //Temp array where we'll store the unsorted bucket dates
    NSMutableArray *unsortedReleaseWeek = [[NSMutableArray alloc] init];
    NSMutableDictionary *tmpDict = [[NSMutableDictionary alloc] init];

    for (NSDictionary *upcomingReleaseDictionary in upcomingReleasesArray) {

        //We find the release date from the string
        NSDate *releaseDate = [dateFormatter dateFromString:[upcomingReleaseDictionary objectForKey:@"release_date"]];

        //We create a new date that ignores everything that is not the actual day (ignoring stuff like the time of the day)
        NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        NSDateComponents *components =
        [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:releaseDate];

        //This will represent our releases "bucket"
        NSDate *bucket = [gregorian dateFromComponents:components];

        //We get the existing objects in the bucket and update it with the latest addition
        NSMutableArray *releasesInBucket = [tmpDict objectForKey:bucket];
        if (!releasesInBucket){
            releasesInBucket = [NSMutableArray array];
            [unsortedReleaseWeek addObject:bucket];
        }

        UpcomingRelease *upcomingRelease = [UpcomingRelease upcomingReleaseWithName:[upcomingReleaseDictionary objectForKey:@"release_name"]];
        upcomingRelease.release_date = [upcomingReleaseDictionary objectForKey:@"release_date"];
        upcomingRelease.release_price = [upcomingReleaseDictionary objectForKey:@"release_price"];
        upcomingRelease.release_colorway = [upcomingReleaseDictionary objectForKey:@"release_colorway"];
        upcomingRelease.release_date = [upcomingReleaseDictionary objectForKey:@"release_date"];
        upcomingRelease.thumb = [upcomingReleaseDictionary valueForKeyPath:@"thumb"];
        upcomingRelease.images = [upcomingReleaseDictionary objectForKey:@"images"];
        [releasesInBucket addObject:upcomingRelease];
        [tmpDict setObject:releasesInBucket forKey:bucket];
    }

    [unsortedReleaseWeek sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSDate* date1 = obj1;
        NSDate* date2 = obj2;
        //This will sort the dates in ascending order (earlier dates first)
        return [date1 compare:date2];
        //Use [date2 compare:date1] if you want an descending order
    }];

    self.releaseWeekDictionary = [NSDictionary dictionaryWithDictionary:tmpDict];
    self.releaseWeek = [NSArray arrayWithArray:unsortedReleaseWeek];

}

One simple方法是使用NSURLConnection的便捷类方法sendAsynchronousRequest:queue:error.

以下代码片段是如何从服务器加载 JSON 以及完成处理程序在解析 JSON 的后台线程上执行的示例。它还执行所有建议的错误检查:

NSURL* url = [NSURL URLWithString:@"http://example.com"];
NSMutableURLRequest* urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest addValue:@"application/json" forHTTPHeaderField:@"Accept"];
NSOperationQueue* queue = [[NSOperationQueue alloc] init];

[NSURLConnection sendAsynchronousRequest:urlRequest
                                   queue:queue
                       completionHandler:^(NSURLResponse* response,
                                           NSData* data,
                                           NSError* error)
{
    if (data) {
        NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
        // check status code and possibly MIME type (which shall start with "application/json"):
        NSRange range = [response.MIMEType rangeOfString:@"application/json"];

        if (httpResponse.statusCode == 200 /* OK */ && range.length != 0) {
            NSError* error;
            id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
            if (jsonObject) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    // self.model = jsonObject;
                    NSLog(@"jsonObject: %@", jsonObject);
                });
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    //[self handleError:error];
                    NSLog(@"ERROR: %@", error);
                });
            }
        }
        else {
            // status code indicates error, or didn't receive type of data requested
            NSString* desc = [[NSString alloc] initWithFormat:@"HTTP Request failed with status code: %d (%@)",
                              (int)(httpResponse.statusCode),
                              [NSHTTPURLResponse localizedStringForStatusCode:httpResponse.statusCode]];
            NSError* error = [NSError errorWithDomain:@"HTTP Request"
                                                 code:-1000
                                             userInfo:@{NSLocalizedDescriptionKey: desc}];
            dispatch_async(dispatch_get_main_queue(), ^{
                //[self handleError:error];  // execute on main thread!
                NSLog(@"ERROR: %@", error);
            });
        }
    }
    else {
        // request failed - error contains info about the failure
        dispatch_async(dispatch_get_main_queue(), ^{
            //[self handleError:error]; // execute on main thread!
            NSLog(@"ERROR: %@", error);
        });
    }
}];

尽管看起来有些复杂,但在我看来,这是一种简约且仍然幼稚的方法。除其他缺点外,主要问题是:

  • 它无法取消请求,并且
  • 没有办法处理更复杂的身份验证。

需要利用更复杂的方法NSURLConnection 代表们。通常,第三方库确实以这种方式实现它,封装了NSURLConnection请求和其他相关状态信息放入子类中NSOperation。您可以从自己的实现开始,例如使用这段代码 https://gist.github.com/couchdeveloper/5764723作为模板。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何异步加载 JSON (iOS) 的相关文章

  • 获取在 iOS UIFont 中追踪字符的路径

    假设我在 iOS 应用程序中使用了自定义字体 Foo 我已将其添加到我的项目 plist 等中 并且我能够渲染UILabels之类的就很好了 现在 如果我想找出可以 追踪 该字体中的字母 P 的点序列 我将如何获得该点序列 例如 假设我想使
  • 更改目录时 Gitlab CI 运行程序作业失败退出状态 1

    我正在使用我的个人机器作为使用 Fastlane 的 iOS 项目的运行程序 这主要是因为共享运行器没有为 iOS 设置 因为它们没有安装 Xcode 更改目录时我的作业立即失败 它是一个 shell 运行程序 根本没有其他自定义配置 有什
  • 使用 Ajax Jquery post 请求进行 Json 劫持

    昨天 我读了一些关于如何预防的好文章使用 Asp Net MVC 进行 Json 劫持 http haacked com archive 2009 06 24 json hijacking aspx 规则是 永远不要通过 get 请求发送
  • iOS 上关键 ClientState 警告的默认访问速度缓慢

    在测试我的 iOS 应用程序时 我收到 对关键 ClientState 的默认访问速度慢 耗时 0 034635 秒 容差为 0 020000 警告 它似乎是间歇性发生的 我试图环顾四周看看它是关于什么的 但我并不完全确定 任何帮助表示赞赏
  • 在 Xcode 中查找未使用的文件

    我最近开始开发一个新应用程序 它基本上是我以前制作的应用程序的副本 但做了一些更改 为了制作这个新应用程序 我复制了旧应用程序并删除了一些不需要的内容 我想知道 有没有办法知道 Xcode 中正在使用哪些类文件 或者有什么关于如何查找未使用
  • Apple 由于崩溃而拒绝了我的应用程序,无法重现它

    我刚刚上传了一个应用程序到应用程序商店 它是为ios 7开发的 他们拒绝了该应用程序 因为我无法重现崩溃 他们向我发送了这份崩溃报告 Exception Type EXC BAD ACCESS SIGSEGV Exception Subty
  • Javascript 将对象推送为克隆

    我将 d3 用于交互式网络应用程序 我需要绑定的数据在交互过程中发生变化 并且由 JSON 变量中的一些选定对象组成 为此 我在 JSON 变量上使用了映射 并进行了一些查询来选择适当的对象 对象被推送到列表中 并且该列表被绑定为新数据 我
  • iOS - 在相机上放置自定义叠加层(垂直对齐)。顶部黑条的大小

    我正在寻找以下问题的编程解决方案 我想在相机 iOS 上绘制自定义叠加层 我希望它位于相机输出视图的垂直中央 我已经完成了相对于屏幕而不是相机图片居中绘制自定义视图 为此 我需要获得顶部黑条的大小 我怎么才能得到它 顶部和底部栏的大小不相等
  • iOS 7 NS 单线程安全合并冲突

    重新排序两行后 在单线程应用程序上保存简单的数据时遇到问题 我已经成功地简化了编码以重现错误 并且希望其他人尝试这一点时得到第二个意见 这是一次健全性检查 因为我怀疑 iOS 7 引入的核心数据问题 而这在 iOS 6 中工作正常 首先 启
  • iOS绘图3D图形库[关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 我正在搜索一个可以帮助我绘制 3D 图表的库 我想要类似的东西这一页 http www math uri edu bkaskosz fla
  • Apache Camel 的 JsonMappingException

    我在骆驼路线上遇到以下异常 Caused by com fasterxml jackson databind JsonMappingException No serializer found for class org apache cam
  • 使用未声明的类型“对象”

    这太奇怪了 通常我可以理解未声明的类 但这是声称 Object 类本身未声明 NSObject 可以工作 但我的项目设置方式我需要它是一个纯 Swift 对象 我的类标题如下所示 import UIKit import Foundation
  • 将 NSFetchedResultsController 添加到项目后出现问题

    我设置 CoreData 时没有NSFetchedResultsController一切都保存得很好 切换到之后NSFetchedResultsController 我在尝试保存图像时遇到奇怪的错误 这是我用来保存图像的代码 void sa
  • 找不到 Cocoa/Cocoa.h 文件

    我在用XMPPFramework在我的应用程序中 我已将 Cocoa Cocoa h 导入到我的 m 文件中 但是当我构建项目时Xcode显示错误 错误 未找到 Cocoa Cocoa h 文件 我该如何解决这个错误 如果您正在为 iOS
  • iOS:如何创建核心数据库的备份副本?以及如何导出/导入该副本?

    我想为我的应用程序的用户提供创建核心数据数据库备份的可能性 特别是在他切换到新设备等情况下 我该怎么做呢 特别是如何重新导入该文件 我的意思是 假设他制作了数据库的备份副本 然后更改了大量内容并想要重置为以前保存的备份副本 我该怎么做呢 T
  • Elm:如何从 JSON API 解码数据

    我有这个数据使用http jsonapi org http jsonapi org format data type prospect id 1 attributes provider user id 1 provider facebook
  • 获取所有ios应用程序的全局列表[重复]

    这个问题在这里已经有答案了 我想对苹果应用商店进行一些全球统计 一个瓶颈是至少获取所有当前活动应用程序的 ID 这 9 位数字 有谁知道如何获取 iOS 应用商店中当前活动应用程序的所有 id 的完整列表 更好的是特定类别的所有 ID 例如
  • 隐藏 UITableview 单元格

    我正在尝试从 UITableView 中隐藏单元格 就像删除操作一样 但我只想隐藏它以便稍后在相同位置显示它 我知道 UITableViewCell 有一个名为 隐藏 的属性 但是当我使用此属性隐藏单元格时 它会隐藏但没有动画 并且会留下空
  • 从应用程序内发送电子邮件中的图像和文本

    如何从我的应用程序内通过电子邮件发送图像和文本 表格数据形式 请大家帮忙并提出建议 谢谢 void sendMailWithImage UIImage image if MFMailComposeViewController canSend
  • iOS 中是否需要 Google App Indexing SDK 才能使用 Google DeepLinking?

    我想用谷歌应用程序索引与我的网页和 iOS 应用程序 我支持通用链接 or 深层链接用谷歌术语 与苹果Search并相应地设置我的网页 From 谷歌文档 https developers google com app indexing i

随机推荐