如何从图像路径获取文件名

时间:2019-02-05 10:13:09

标签: ios swift4

我正在尝试从图像路径URL获取文件名 但我遇到类似“无法在强制转换中将'URL'类型的值转换为'NSString'类型的错误”之类的错误,谁能帮助我将其转换为NSstring。谢谢!

if var imgUrl = info[UIImagePickerController.InfoKey.imageURL] as? URL{
    let imgName = imgUrl.lastPathComponent
    let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
    let localPath = documentDirectory?.appending(imgName)

    var image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
    let data = image.pngData()! as NSData
    data.write(toFile: localPath!, atomically: true)
    //let imageData = NSData(contentsOfFile: localPath!)!
    let photoURL = URL.init(fileURLWithPath: localPath!)//NSURL(fileURLWithPath: localPath!)
    print(photoURL)

    let filename = (photoURL as NSString).lastPathComponent
    // pdfURL is your file url
    let fileExtention = (filename as NSString).pathExtension  // get your file extension
    let pathPrefix = (filename as NSString).deletingPathExtension
    img.image = image

1 个答案:

答案 0 :(得分:3)

(在Swift中)所有用于路径操作的方法都在URL结构中。无需转换

let filename = photoURL.lastPathComponent
// pdfURL is your file url
let fileExtention = photoURL.pathExtension  // get your file extension
let pathPrefix = photoURL.deletingPathExtension.lastPathComponent
img.image = image

如果存在本机等效项,则根本不要在Swift中使用NS类。


请考虑

之类的警​​告
  

可变的“图像”从未改变过;考虑更改为“ let”常量