【发布时间】:2019-04-14 13:44:15
【问题描述】:
我是一个相当不错的 Objective C 开发人员,我现在正在学习 Swift(我觉得这很困难,这不仅是因为新概念,例如可选项,还因为 Swift 不断发展,而且很多可用的教程严重过时)。
目前我正在尝试将 JSON 从 url 解析为 NSDictionary,然后使用它的一个值来显示图像(这也是一个 url)。像这样的:
URL -> NSDictionary -> 从 url 初始化 UIImage -> 在 UIImageView 中显示 UIImage
这在 Objective C 中很容易(甚至可能有更简短的答案):
NSURL *url = [NSURL URLWithString:@"https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY"];
NSData *apodData = [NSData dataWithContentsOfURL:url];
NSDictionary *apodDict = [NSJSONSerialization JSONObjectWithData:apodData options:0 error:nil];
上面的代码sn-p给了我一个标准的NSDictionary,我可以在其中引用“url”键来获取我要显示的图片的地址:
“网址”:“https://apod.nasa.gov/apod/image/1811/hillpan_apollo15_4000.jpg”
然后我将其转换为 UIImage 并将其提供给 UIImageView:
NSURL *imageURL = [NSURL URLWithString: [apodDict objectForKey:@"url"]];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *apodImage = [UIImage imageWithData:imageData];
UIImageView *apodView = [[UIImageView alloc] initWithImage: apodImage];
现在,我基本上是在尝试在 Swift 中复制上述 Objective C 代码,但不断遇到困难。我已经尝试了几个教程(其中一个实际上做了完全相同的事情:显示 NASA 图像),并找到了一些堆栈溢出答案,但没有一个可以提供帮助,因为它们要么已经过时,要么做的事情与我需要的不同。
所以,我想请社区为这些问题提供 Swift 4 代码:
1. Convert data from url into a Dictionary
2. Use key:value pair from dict to get url to display an image
如果还不算太多,我还想在代码旁边要求详细描述,因为我希望答案是我认为目前在任何地方都没有的针对此任务的一个全面的“教程”。
谢谢!
【问题讨论】:
-
在 Swift 中你应该使用
URL,而不是NSURL。使用Data,而不是NSData。使用 Swift 字典,而不是NSDictionary。
标签: ios json swift nsdictionary