파일 경로에서 파일 이름을 신속하게 가져오는 방법
지정된 파일 경로 문자열에서 파일 이름을 가져오는 방법은 무엇입니까?
예를 들어 다음과 같은 파일 경로 문자열이 있는 경우
file:///Users/DeveloperTeam/Library/Developer/CoreSimulator/Devices/F33222DF-D8F0-448B-A127-C5B03C64D0DC/data/Containers/Data/Application/5D0A6264-6007-4E69-A63B-D77868EA1807/tmp/trim.D152E6EA-D19D-4E3F-8110-6EACB2833CE3.MOV
그리고 저는 반품 결과를 받고 싶습니다.
trim.D152E6EA-D19D-4E3F-8110-6EACB2833CE3.MOV
목표 C
NSString* theFileName = [string lastPathComponent]
스위프트
let theFileName = (string as NSString).lastPathComponent
SWIFT 3.x 또는 SWIFT 4: 가장 짧고 깨끗한 방법은 다음과 같습니다.이 예에서는url
변수는 다음의 유형입니다.URL
이런 식으로 우리는 읽을 수 있는 인간을 가질 수 있습니다.String
다음과 같은 확장자를 가진 전체 파일 이름의 결과입니다.My file name.txt
그리고 닮지 않은My%20file%20name.txt
// Result like: My file name.txt
let fileName = url.lastPathComponent
로깅 목적 등으로 현재 파일 이름을 얻고자 하는 경우 이를 사용합니다.
스위프트 4
URL(fileURLWithPath: #file).lastPathComponent
스위프트 2:
var file_name = NSURL(fileURLWithPath: path_to_file).lastPathComponent!
let theURL = URL(string: "yourURL/somePDF.pdf") //use your URL
let fileNameWithExt = theURL?.lastPathComponent //somePDF.pdf
let fileNameLessExt = theURL?.deletingPathExtension().lastPathComponent //somePDF
이 기능이 작동하려면 URL이 문자열이 아닌 유형의 URL이어야 하므로 미리 문자열로 변환하지 마십시오.
이 코드를 복사하여 플레이그라운드에 직접 붙여넣어 작동 방식을 확인할 수 있습니다.
사용해 보세요.
let filename: String = "your file name"
let pathExtention = filename.pathExtension
let pathPrefix = filename.stringByDeletingPathExtension
업데이트됨:
extension String {
var fileURL: URL {
return URL(fileURLWithPath: self)
}
var pathExtension: String {
return fileURL.pathExtension
}
var lastPathComponent: String {
return fileURL.lastPathComponent
}
}
도움이 되길 바랍니다.
아래 코드는 스위프트 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
아래와 같이 fileUrl에 URL을 전달할 수 있습니다.
let fileUrl: String = "https://www.himgs.com/imagenes/hello/social/hello-fb-logo.png" // Pass the URL
let lastPathComponent = URL.init(string: fileUrl)?.lastPathComponent ?? "" // With this you will get last path component
let fileNameWithExtension = lastPathComponent
//이 마지막 경로 구성 요소는 확장명을 가진 파일 이름을 제공합니다.
몇 가지 성능 테스트(iOS 14, 실제 장치, 릴리스 구성)를 수행했습니다.
(#file as NSString).lastPathComponent // The fastest option.
URL(string: #file)!.lastPathComponent // 2.5 times slower than NSString.
#file.components(separatedBy: "/").last! // 7 times slower than NSString.
보너스:
URL(fileURLWithPath: #file, isDirectory: false).lastPathComponent // About the same as URL(string:).
URL(fileURLWithPath: #file).lastPathComponent // 2.5 times slower than with explicit isDirectory.
스위프트 5.이것은 둘 다보다 더 빨리 작동합니다.URL
그리고.NSString
옵션:
path.components(separatedBy: "/").last
Swift >= 4.2의 URL에서 확장자 없이 파일 이름을 검색하려면:
let urlWithoutFileExtension: URL = originalFileUrl.deletingPathExtension()
let fileNameWithoutExtension: String = urlWithoutFileExtension.lastPathComponent
두 개의 이전 폴더를 포함하는 고유한 "파일 이름" 양식 URL을 만듭니다.
func createFileNameFromURL (colorUrl: URL) -> String {
var arrayFolders = colorUrl.pathComponents
// -3 because last element from url is "file name" and 2 previous are folders on server
let indx = arrayFolders.count - 3
var fileName = ""
switch indx{
case 0...:
fileName = arrayFolders[indx] + arrayFolders[indx+1] + arrayFolders[indx+2]
case -1:
fileName = arrayFolders[indx+1] + arrayFolders[indx+2]
case -2:
fileName = arrayFolders[indx+2]
default:
break
}
return fileName
}
언급URL : https://stackoverflow.com/questions/31780453/how-to-get-the-filename-from-the-filepath-in-swift
'it-source' 카테고리의 다른 글
Excel에서 범위의 각 행을 반복합니다. (0) | 2023.05.31 |
---|---|
Cocoapod를 사용할 때 Xcode 경고 무시 (0) | 2023.05.31 |
Android 오류: *.apk를 장치에 설치하지 못했습니다 *: 시간 초과 (0) | 2023.05.31 |
PowerShell에서 로컬 호스트 이름을 가져오려면 어떻게 해야 합니까? (0) | 2023.05.31 |
Mongoose 문자열 키에 Json 개체 저장 (0) | 2023.05.31 |