使用SWIFT以编程方式计算assets.xcassets路径

时间:2015-12-23 21:44:00

标签: ios objective-c swift path icloud

尝试用快速代码计算图像的路径。我得到了这个,我认为在目标C中有效。

[UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.png", [[NSBundle mainBundle] resourcePath], imgName]];

要获取我的.png图像的路径,我存储在assets.xcassets中。但我现在需要在SWIFT中这样做,而不是客观的C.

我需要路径,因为我试图将我放在那里的图像上传到iCloud中的CKAsset

1 个答案:

答案 0 :(得分:17)

如果您只需要文件的路径(而不是UIImage的实例),则会执行此操作:

Swift 2:

if let resourcePath = NSBundle.mainBundle().resourcePath {
    let imgName = "dog.png"
    let path = resourcePath + "/" + imgName
}

Swift 3/4:

if let resourcePath = Bundle.main.resourcePath {
    let imgName = "dog.png"
    let path = resourcePath + "/" + imgName
}