Extracting string after x number of backlashes in swift - swift

I can't find any way to extract a certain string value from another string in SwiftUi.
It is the following link:
"http://media.site.com/videos/3070/0003C305B74F77.mp4"
How would you go about extracting the numbers 0003C305B74F77?

It would be much easier to treat it as an URL. That's what it is. All you need it to get its last path component after deleting its path extension.
let link = "http://media.site.com/videos/3070/0003C305B74F77.mp4"
if let url = URL(string: link) {
let lastPathComponent = url.deletingPathExtension().lastPathComponent
print(lastPathComponent) // "0003C305B74F77"
}

Related

Split String with varied amount of input data

I have a string that looks like this:
https://product/000000/product-name-type-color
I used a split to separate this strings, but Im having problems because the link can come without the description or the id
guard let separateLink = deeplink?.split(separator: "/") else { return }
let linkWithoutProductDetails = "\(separateLink[0] ?? "")//\(separateLink[1] ?? "")/\(separateLink[2] ?? "")"
When the link comes only https://product/ Im getting Fatal error: Index out of range even using the Optionals and String Interpolation, how can i guarantee that independently of the quantity of informations in my link the code wont break
You should check the number of path components. However, ideally you should use the URL functions instead of manipulating the link as a String:
if var url = URL(string: "https://product/000000/product-name-type-color") {
let pathComponents = url.pathComponents
// "product" is not a path component, it's the host.
// Path components are "/", "000000" and "product-name-type-color"
if pathComponents.count > 2 {
url = url.deletingLastPathComponent()
}
print(url)
}

MacOS how is KIND implemented

I am trying to write a piece of code that instead of checking file extensions for the many different types of image files, but instead looking at the file attributes. What I can’t figure out from searching the docs is if KIND:Image is really a file attribute or simply a construct Apple created in the FinderApp to make things easier for the user.
I wrote a snippet that pulls the attributes for files with an extension of jpeg and for each file the fileType is returned as NSFileTypeRegular.
let attr = try filemanager.attributesOfItem(atPath: pathConfig+"/"+file) as NSDictionary
if file.hasSuffix(ext) {
   print ("Adding \(file) [ \(attr.fileSize()) \(attr.fileType())]")
   print ( attr.fileModificationDate() )
}
Does anybody know if MacOS retains an attribute for the category a file falls in to. e.g. IMAGE, DOCUMENT etc.
To achieve a functionality similar to the Kind search tag in Finder you can use UTType (Link to reference).
You can get the UTType of a file by initialising it with the file extension:
let fileType = UTType(filenameExtension: fileURL.pathExtension)
The cool thing about UTTypes is that they have a hierarchy, for example, UTType.jpeg is a subtype of UTType.image, along with others like .png.
If you want to check if a file is any kind of image, you can do it like this
let isImage = fileType.conforms(to: .image)
You can check the list for the kind of types you want to support as "Kinds", and filter using those UTTypes
This was my final solution based on the information provided by #EmilioPelaez I am not completely comfortable with Swift especially the unwrapping operations so if the code looks weird that might be why.
func imagesInDir(path: String?) -> [String] {
if let path {
let filemanager: FileManager = FileManager()
let files = filemanager.enumerator(atPath: path)
var array = [String]()
var urlFile: NSURL
while let file = files?.nextObject() as? String {
urlFile = NSURL(fileURLWithPath: file, isDirectory: false)
if (urlFile.isFileURL) {
if let pathExt = urlFile.pathExtension {
if let fileType = UTType(filenameExtension: pathExt) {
let isImage = fileType.conforms(to: .image)
if (isImage){
array.append(file)
print ("\(array.count) \(fileType)")
}
}
}
}
}
}
return array
}

Find specific character from URL Link

How can I find out specific character from URL String variable using Swift 3?
i want to get the value out of the URLlink(image is given) user_lati,user_long,destination_lat,destinaton_long and save it.
Can any one give me the solution for this?
I have given a couple of examples below. You should really check the documentation for String, URL and Collections
let urlString = "https://www.example.com/search?q=test&user=john"
let url = URL(string: urlString)!
print(url.query) // q=test&user=john
print(urlString.index(of: "?")?.encodedOffset) // 30 - index of ?
print(url.absoluteString.index(of: "?")?.encodedOffset) // same as above

Delete parameter from URL with swift

I have an URL that looks like myapp://jhb/test/deeplink/url?id=4567 .
I want to delete every thing after the ? char. At the end the URL should look like myapp://jhb/test/deeplink/url. how. can I achieve that? convert the url to a string? Regex?
Use URLComponents to separate the different URL parts, manipulate them and then extract the new url:
var components = URLComponents(string: "myapp://jhb/test/deeplink/url?id=4567")!
components.query = nil
print(components.url!)
myapp://jhb/test/deeplink/url
A convenient extension on URL
private extension URL {
var removingQueries: URL {
if var components = URLComponents(string: absoluteString) {
components.query = nil
return components.url ?? self
} else {
return self
}
}
}
can I achieve that? convert the url to a string? Regex?
When working with URLs, it would be better to treat it as URLComponent:
A structure that parses URLs into and constructs URLs from their
constituent parts.
therefore, referring to URLComponent what are you asking is to remove the the query subcomponent from the url:
if var componenets = URLComponents(string: "myapp://jhb/test/deeplink/url?id=4567") {
componenets.query = nil
print(componenets) // myapp://jhb/test/deeplink/url
}
Note that query is an optional string, which means it could be nil (as mentioned in the code snippet, which should leads to your desired output).
You can do like this
let values = utl?.components(separatedBy: "?")[0]
It will break the string with ? and return the array.
The first object of values give you your resultant string.
You can get each URL component separated from URl using
print("\(url.host!)") //Domain name
print("\(url.path)") // Path
print("\(url.query)") // query string

How can I get all text from a PDF in Swift?

I have a PDF document and would like to extract all its text.
I tried the following:
import Quartz
let url = NSBundle.mainBundle().URLForResource("test", withExtension: "pdf")
let pdf = PDFDocument(URL: url)
print(pdf.string())
It does get the text, however the order of the lines extracted is completely mixed up as compared to opening the PDF in Adobe, Edit Select All, Copy, Paste!
How can I get the same outcome in Swift, as opening the PDF, Select All, Copy/Paste!?
If you want only text content:
extension String
{
func readPDF() -> String
{
let path = "\(self)"
let url = URL(fileURLWithPath: path)
let pdf = PDFDocument(url: url)
return pdf!.string!
}
}
I did it. with this:
if let pdf = PDFDocument(url: url) {
let pageCount = pdf.pageCount
let documentContent = NSMutableAttributedString()
for i in 1 ..< pageCount {
guard let page = pdf.page(at: i) else { continue }
guard let pageContent = page.attributedString else { continue }
documentContent.append(pageContent)
}
}
Hope it helps.
That is unfortunately not possible.
At least not without some major work on your part. And it certainly is not possible in a general matter for all pdfs.
PDFs are (generally) a one-way street.
They were created to display text in the same way on every system without any difference and for printers to print a document without the printer having to know all fonts and stuff.
Extracting text is non-trivial and only possible for some PDFs where the basic image-pdf is accompanied by text (which it does not have to). All text information present in the PDF is coupled with location information to determine where it is to be shown.
If you have a table shown in the PDF where the left column contains the names of the entries and the right row contains its contents, both of those columns can be represented as completely different blocks of text which only appear to have some link between each other due to the their placement next to each other.
What the framework / your code would have to do is determine what parts of text that are visually linked are also logically linked and belong together. That is not (yet) possible. The reason you and I can read and understand and group the PDF is that in some fields our brain is still far better than computers.
Final note because it might cause confusion: It is certainly possible that Adobe and Apple as well do some of this grouping already and achieves a good result, but it is still not perfect. The PDF I just tested was pretty mangled up after extracting the text via the Mac Preview.
Here's an option using PDFKit:
import Cocoa
import Quartz
func pdfToText(fromPDF: String) -> String {
let urlPath = Bundle.main.url(forResource: fromPDF, withExtension: "pdf")
let docContent = NSMutableAttributedString()
if let pdf = PDFDocument(url: urlPath!) {
let pageCount = pdf.pageCount
for i in 1 ..< pageCount {
guard let page = pdf.page(at: i) else { continue }
guard let pageContent = page.attributedString else { continue }
docContent.append(pageContent)
}
}
return docContent.string
}
let pdfString = pdfToText(fromPDF: "documentName")
This gives you the option to get the PDF content as an attributed string. If you're just after the plain text, you can get it by attaching .string to the result like I did in the above example.
cf. Paul Hudson's snippet
Apple's documentation for the PDFDocument class says that string is "a convenience method, equivalent to creating a selection object for the entire document and then invoking the PDFSelection class’s string method."
So you should get the same results using it as copying and pasting in Preview.
Adobe's Acrobat may use some other routine to create a more logically useful flow, but you can't access that programmatically in MacOS.