Delete parameter from URL with swift - 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

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)
}

Extracting string after x number of backlashes in 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"
}

How do I fetch HTML of URL using Vapor Swift?

In one of my routes, I want to fetch HTML from a different site. https://docs.vapor.codes/4.0/content/ documents support for JSON and such but I couldn't find anything on raw HTML.
request.client.get(URI(string: "https://example.com/")).map { (response: ClientResponse) -> String? in
if response.status == .ok && response.content.contentType == .html {
return response.content... // How do I get raw html?
}
return nil
}
How do I get the raw HTML from the client response?
There are a couple of ways you can do this, depending on which String initializer you happen to fancy. Note that to use any of the following methods, you will need to unwrap the response body first:
guard let body = response.body else {
throw Abort(.internalServerError)
}
The first way is using the ByteBuffer.readString method.
guard let html = body.readString(length: body.readableBytes) else {
throw Abort(.internalServerError)
}
Another way is to use the String(decoding:as:) initializer, which can be used to convert any collection of UInt8 integers to a String:
let html = String(decoding: body.readableBytesView, as: UTF8.self)
Anf finally, you can use the String(buffer:) initializer that #iMike suggested.
let html = String(buffer: body)
Keep in mind that the .readBytes method will increment the .readIndex of the ByteBuffer, while the String initializers won't. Though I imagine that this doesn't really matter in your case.

Prepare String for URL cast in Swift

I have a text Area, the content of which will later be used to create a URL. How can I validate that the url - cast doesn't throw an error? Is there a function that can do that? For example remove all invalid Characters. I cast the String in the following way, but if the user inputs a newline the cast doesn't work:let url: URL = URL(string: urlPath)!
Use optional binding (https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html):
var str = "somescheme://somedata"
if let url = URL(string: str) {
// handle url
} else {
// handle error
}
If you want to strip whitespaces and new line characters, use:
str.trimmingCharacters(in: .whitespacesAndNewlines)

Delete parameter from json URL with swift3

I have a URL that looks like 123456_https://example.com.
I want to delete every thing before the _https: part. At the end, the URL should look like https://example.com.
How can I achieve that?
If the prefix is always a couple of characters ending with a underscore you can use this regular expression
let url = "123456_https://example.com"
let trimmedURL = url.replacingOccurrences(of: "^\\w+_", with: "", options: .regularExpression)
you can do something like this if you do not know how to use Regular Expressions
// url string
var url = "123456_https://example.com"
// seperate url by "_" and provides 123456 and https://example.com in urlArray
let urlArray = url.components(separatedBy: "_")
// now to be safe
if(urlArray.count == 2){
// here you get your desired string
let myUrl = urlArray[1]
}