How to get the filename from the filepath in swift

后端 未结 10 1476
一生所求
一生所求 2020-12-04 20:47

How to get the filename from the given file path string?

For example if I have a filepath string as

file:///Users/DeveloperTeam/Library/Developer/Co         


        
相关标签:
10条回答
  • 2020-12-04 21:23

    Swift 2:

    var file_name = NSURL(fileURLWithPath: path_to_file).lastPathComponent!
    
    0 讨论(0)
  • 2020-12-04 21:25

    Below code is working for me in Swift 4.X

     let filename = (self.pdfURL as NSString).lastPathComponent  // pdfURL is your file url
     let fileExtention = (filename as NSString).pathExtension  // get your file extension
     let pathPrefix = (filename as NSString).deletingPathExtension   // File name without extension
     self.lblFileName.text = pathPrefix  // Print name on Label
    
    0 讨论(0)
  • 2020-12-04 21:27

    Objective C

    NSString* theFileName = [string lastPathComponent]
    

    Swift

    let theFileName = (string as NSString).lastPathComponent
    
    0 讨论(0)
  • 2020-12-04 21:28

    If you want to get the current file name such as for logging purposes, I use this.

    Swift 4

    URL(fileURLWithPath: #file).lastPathComponent
    
    0 讨论(0)
提交回复
热议问题