简体   繁体   English

从XCAsset目录中获取数据

[英]Get Data from XCAsset catalog

I understand that to get images from the asset catalog i can use UIImage(named: "fileName") to do it. 我理解为了从资产目录中获取图像,我可以使用UIImage(名为:“fileName”)来完成它。

however, what if i am getting DATA from the XCAsset catalog? 但是,如果我从XCAsset目录中获取数据怎么办? I can't figure this out. 我无法弄清楚这一点。

I have tried, 我试过了,

let url = NSBundle.mainBundle().URLForResource("fileName", withExtension: nil)
let data = NSData(contentsOfURL: url!)

But it is nil. 但它没有。 I do not know how to get data from the XCAssets catalog. 我不知道如何从XCAssets目录中获取数据。 If anyone can help me out (googling hasn't helped) please let me know I will be very thankful! 如果有人可以帮助我(谷歌搜索没有帮助),请让我知道我会非常感激!

Update: 更新:

Why am I trying to get data from an asset catalog? 为什么我要从资产目录中获取数据? I dragged an animated gif into the asset catalog. 我将动画gif拖入资产目录。 And the asset catalog interprets that as DATA. 资产目录将其解释为DATA。 This is why I am trying to get data out of the asset catalog. 这就是我试图从资产目录中获取数据的原因。

Update: This is a screen shot of my Assets.xcassets folder looks like. 更新:这是我的Assets.xcassets文件夹的屏幕截图。

图片 It has a file called "_Loading" and on the right it is considered a "Data set". 它有一个名为“_Loading”的文件,在右边它被认为是“数据集”。 I'm not sure how to get the data set from the Assets catalog. 我不确定如何从Assets目录中获取数据集。

I am going to answer my own question. 我将回答我自己的问题。

Since iOS 9, the Asset Catalog allows more than just Images. 从iOS 9开始,资产目录不仅仅包含图像。 They allow Data sets. 它们允许数据集。 In order to get data from the Asset Catalog, you must use the NSDataAsset class. 要从资产目录中获取数据,必须使用NSDataAsset类。

Example: Assume you have an Data Asset named "CoolJSON" 示例:假设您有一个名为“CoolJSON”的数据资产

if let asset = NSDataAsset(name: "CoolJSON") {
    let data = asset.data
    let d = try? NSJSONSerialization.JSONObjectWithData(data, options: [])
}

In this example I turned an NSData object into a json. 在这个例子中,我将NSData对象转换为json。

NSDataAsset class reference NSDataAsset类引用

Load gif image from Assets.xcassets file. 从Assets.xcassets文件加载gif图像。 That`s same for loading json files. 这与加载json文件相同。

  1. NEW: 【New Data Set】 crate a data set and rename "funny" in Assets.xcassets folder. 新:【新数据集】创建数据集并在Assets.xcassets文件夹中重命名为“funny”。 all right, the gif file is added to Assets.xcassets folder. 好吧,gif文件被添加到Assets.xcassets文件夹中。 在此输入图像描述

  2. USE: 使用:

     NSDataAsset *asset = [[NSDataAsset alloc] initWithName:@"funny"]; self.gifImageView.image = [UIImage sd_animatedGIFWithData:asset.data]; 
    • (UIImage *)sd_animatedGIFWithData:(NSData *)data: is a UIImage+GIF category for loading gif image in SDWebImage. (UIImage *)sd_animatedGIFWithData:(NSData *)data:是用于在SDWebImage中加载gif图像的UIImage + GIF类别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM