【问题标题】:Issue with file manager in swift 3.1swift 3.1 中的文件管理器问题
【发布时间】:2017-04-05 03:29:36
【问题描述】:

在 swift 3.1 发布之前,我的以下代码运行良好。

func loadImage() {

    id = userPhotoModel.id

    let fileManager = FileManager.default

    let imagePath = (self.getDirectoryPath() as NSString).appendingPathComponent(photoName)

    if fileManager.fileExists(atPath: imagePath){
        let imageFromPath = resizeImage(named: (contentsOfFile: imagePath))

        print("name of photo retrieved: \(photoName)")

        self.userPhoto.image = imageFromPath

    }else{
        print("No Image")
    }
}

现在,swift 3.1 想要添加 as!字符串到:

let imageFromPath = resizeImage(named: (contentsOfFile: imagePath) as! String)

但是,当我运行该应用程序时,它会在此位置崩溃,并且没有错误消息,如下图所示。

这是什么原因造成的?

编辑:这里是 resizeImage 函数

fileprivate func resizeImage(named name: String) -> UIImage
{

    var image = UIImage(named: name)

    if image!.size.height > image!.size.width
    {
        self.userPhoto.contentMode = .scaleAspectFit
    }
    else
    {
        image = image!.resizeTo(self.userPhoto.bounds)
    }
    return image!
}

【问题讨论】:

  • 什么是resizeImage 及其声明? (contentsOfFile: imagePath) 应该是什么表达式?
  • 我允许用户添加自己的图像。这是我使用现有名称并将“_full”.jpg 添加到每个图像的地方(以匹配已加载的当前图像)。此文件名被附加到 imagePath。
  • 但是该表达式的contentsOfFile: 部分是什么?为什么这条线不简单:let imageFromPath = resizeImage(named: imagePath)
  • 老实说,不记得为什么我添加了那个额外的步骤,但你的建议有效并修复了它。把它作为答案,我会接受的。谢谢

标签: swift xcode8 ios10 swift3.1


【解决方案1】:

问题在于该行中令人困惑的语法:

let imageFromPath = resizeImage(named: (contentsOfFile: imagePath))

应该是这样的:

let imageFromPath = resizeImage(named: imagePath)

在任何 Swift 3.x 中都不需要强制转换。

【讨论】:

    猜你喜欢
    • 2014-04-02
    • 2013-11-10
    • 2020-10-18
    • 2023-03-28
    • 1970-01-01
    • 2017-08-26
    • 2020-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多