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

Ios 使用SWIFT以编程方式计算assets.xcsets路径,ios,objective-c,swift,path,icloud,Ios,Objective C,Swift,Path,Icloud,试图用swift代码找出图像的路径。我得到了这个,我认为在目标C中有效 [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.png", [[NSBundle mainBundle] resourcePath], imgName]]; 要获取存储在assets.xcsets中的.png图像的路径。但我现在需要用SWIFT,而不是objective C 我需要路径,因为我正在尝试将我放在那里的图像上载到iCloud

试图用swift代码找出图像的路径。我得到了这个,我认为在目标C中有效

[UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.png", [[NSBundle mainBundle] resourcePath], imgName]];
要获取存储在assets.xcsets中的.png图像的路径。但我现在需要用SWIFT,而不是objective C


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

如果您只需要文件的路径(而不是
UIImage
的实例),则可以:

Swift 2:

if let resourcePath = NSBundle.mainBundle().resourcePath {
    let imgName = "dog.png"
    let path = resourcePath + "/" + imgName
}
if let resourcePath = Bundle.main.resourcePath {
    let imgName = "dog.png"
    let path = resourcePath + "/" + imgName
}
Swift 3/4:

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

谢谢James,这种方法只适用于我需要在resourcePath+imgName之间添加一个/between,最后我只得到了一个主捆绑包的文件路径,因此无法访问assets.xcsets dog.png图像。嘿@user3069232,呃。。。忘了正斜杠!我已经更新了代码,请参阅我的编辑。我猜否决票是因为它没有按照规定回答问题。这将无法访问存储在xcassets中的图像文件。这些图像被编译成一个名为Assets.car的文件,因此无法通过路径名直接访问。