简体   繁体   English

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

[英]how to get the file name from image path

i am trying to get the file name from image pathurl but i am getting an error like "Cannot convert value of type 'URL' to type 'NSString' in coercion"can anyone help me to convert as NSstring .Thanks in advance 我正在尝试从图像路径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

(In Swift) all methods for path manipulation are in the URL struct. (在Swift中)所有用于路径操作的方法都在URL结构中。 No conversion needed 无需转换

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

And don't use NS classes in Swift at all if there is a native equivalent. 如果存在本机等效项,则根本不要在Swift中使用NS类。


And please consider warnings like 并且请考虑以下警告

Variable 'image' was never mutated; 可变的“图像”从未改变。 consider changing to 'let' constant 考虑更改为“ let”常量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM