I need to decide the filetype of a file from the filename which I get in string. So I decided to get the last three characters of the String to decide what filetype it is. How do I get the last three characters in a String. For example
var fileName = "test.pdf"
I need to get the pdf alone. Is there any other better way to check for the file type other than this. Please suggest me that also. Because I think, I won be able to recognise if the filetype comes in four characters like "jpeg" and other stuff. Thanks in advance.
I think you are looking for :
The path extension, if any, of the string as interpreted as a path. (read-only) Declaration
Swift
var pathExtension: String { get }
Discussion
The path extension is the portion of the last path component which follows the final period, if there is one. The extension divider is not included. The following table illustrates the effect of pathExtension
on a variety of different paths:
Receiver's String Value
String Returned
“/tmp/scratch.tiff” “tiff”
Example :
file.pathExtension
As of Swift 2.x, pathExtension
is no longer available for the String
class.
You can instead cast to NSString
and do:
let filename = "test.pdf"
let extension = (filename as NSString).pathExtension
let filename: String = "test.pdf"
let pathExtention = filename.pathExtension
download This File from DropBox add to your Project and use like this
if let fileURL = URL(string: newURL){
let fileUTI = UTI(withExtension: fileURL.pathExtension)
switch fileUTI {
case .pdf:
print("add PDF Options")
self.selecteFileMemeTyp = fileUTI.mimeType!
self.addAllPDFOptions()
case .jpeg:
print("add jpg Options")
case .png:
print("add png Options")
case .tiff:
print("add tiff Options")
case .gif:
print("add gif options")
case .spreadsheet:
print("add excel Options")
case .html:
print("add html options")
case .zipArchive:
print("add zip Options")
break
case .docx , .doc:
print("add dox options")
default:
print("default")
} }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.