如何在Swift 3中将文档目录中的图像显示到UIImageView?

Ark*_*yan 6 swift3

下面的Swift 2示例给出了以下错误:

String类型的值没有成员'stringByAppendingPathComponent'

错误的屏幕截图

我需要为Swift 3更改什么?

Cod*_*ent 5

Apple试图将所有人从URL(即file:///path/to/file.text)的路径范式转移到URL(即).Swift API几乎完全取消pathURL.

你仍然可以在Objective-C(NSString)中找到它:

let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let getImagePath = NSString.path(withComponents: [paths, "fileName"])
Run Code Online (Sandbox Code Playgroud)

Swifty方式越多:

let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = URL(fileURLWithPath: paths).appendingPathComponent("fileName")
Run Code Online (Sandbox Code Playgroud)

  • 如果您决定使用URL,请调用`path`属性以获取路径为字符串:`myImage.image = UIImage(contentsOfFIle:imageUrl.path)` (2认同)