How to append a string to a URL in Swift? - swift

Given a name of a file like this:
let fileName = "example.jpg"
I am grabbing the URL of this directory using a helper function, which returns the URL to me:
let imagesURL = getURL()
How can I append the string fileName to the imagesURL such that it returns something like this:
/path/to/images/dir/example.jpg
How do I get it in both String and URL format?

This gives you a new URL with the fileName appended:
let appended = imagesURL.appendingPathComponent(fileName)
And this converts it back to a string:
let strVersion = appended.absoluteString //full URL
let strVersion2 = appended.path //path only

url.appendingPathComponent(fileName)
has been deprecated, use
url.appending(path: filename) instead.

Related

Using String addingPercentEncoding to encode a string as query param

I have an input string "+20" and I am trying to pass that as query parameter in url.
So I am trying to encode the myInputString by doing
let s1 = myInputString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
But in the debugger, the string s1 still shows as '+20' instead of '%2B20'
Is there something I did wrong?
As already mentioned by matt + is a legal URL character. If you really need to encode it you would need to create your own custom urlQueryAllowed and subtract the plus sign from it:
extension CharacterSet {
static let allowedCharacters = urlQueryAllowed.subtracting(.init(charactersIn: "+"))
}
let myInputString = "+20"
let s1 = myInputString.addingPercentEncoding(withAllowedCharacters: .allowedCharacters) // "%2B20"

How to convert Array of string to Array of URL?

Need to convert array of string value to array of URL. Some one help me to convert the String array to URL array in swift.
let urls = ["www.1.com", "www.1.com", "www.1.com", "randomSmth"].compactMap { URL(string: $0) }
"compactMap" ensures that it just ignores invalid urls.
Use compact map to filter non valid URLs
let arrayOfStrings = ["https://www.google.com","https://www.facebook.com", "notRerallyAnURL"]
let arrayOfURLs = arrayOfStrings.compactMap { URL(string:$0) }

Substrings in Swift 4

I have a url string (fake)
http://fools.sayers.mine.cs/api/analytics/ces_ssn
And I'd like to create a new URL string
http://fools.sayers.mine.cs/api/
The issue I'm facing is the last parameter ces_ssn can sometimes be anything like ces_fw or adv_let so I can't entirely set an endIndex in my code.
Is there a way to create a function that is dynamic in saying just give me the first 32 characters every time, not matter the endIndex
You have a URL. Use URL. Assuming you know you want to drop the last two parts of the path, you can do:
let myURL = URL(string: "http://fools.sayers.mine.cs/api/analytics/ces_ssn")!
let shortURL = myURL.deletingLastPathComponent().deletingLastPathComponent()
print(shortURL)
Output:
http://fools.sayers.mine.cs/api/
This works for Swift 4
var url = "http://fools.sayers.mine.cs/api/analytics/ces_ssn"
let newStr = url.prefix(32)
or probably the perfect way
if let index = url.range(of: "api/")?.upperBound {
let api = url.prefix(upTo: index)
}
You can use prefix()
"http://fools.sayers.mine.cs/api/analytics/ces_ssn".prefix(32)
That sounds prone to mistake if all of a sudden your URL is https instead of http, for example.
Instead I would do:
let url = URL(string: "http://fools.sayers.mine.cs/api/analytics/ces_ssn")!
let components = url.pathComponents
let scheme = url.scheme!
let host = url.host!
let slash = components.removeFirst()
print (components) // ["api", "analytics", "ces_ssn"]
The components you are interested in are then the 0 and 1 component, and you could reconstruct your URL like this:
let newURL = "\(scheme)://\(host)/\(components[0])/\(components[1])"
print (newURL) // "http://fools.sayers.mine.cs/api/analytics"

How to convert String with " character to URL

How to convert String like "fff\"fff" to URL?
URL must contain " character and be like "ff"ff"
You escape the " character to %22. The easiest way to do that is via URLComponents:
var components = URLComponents(string: "https://somewhere.com")!
components.query = "ff\"ff"
let url = components.url! // https://somewhere.com?ff%22ff

Base64Encoding result string with "/" in Swift

I want to convert a UIImage to a string representation. I am using the following code:
let imageData = UIImagePNGRepresentation(resizedImage)
if let imageBase64 = imageData?.base64EncodedDataWithOptions(NSDataBase64EncodingOptions (rawValue: 0)) {
let strBase64:String = imageBase64.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
}
The resulting string looks something like:
aVZCT1J3MEtHZ29BQUFBTlNVaEVVZ0FBQWZRQUFBRk5DQUlBQUFCNWNRcGdBQUFBQVhOU1IwSUFyczRjNlFBQUFCeHBSRTlVQUFBQUFnQUFBQUFBQUFDbkFBQUFLQUFBQUtjQUFBQ21BQUg4T0dIYnkwY0FBRUFBU1VSQlZIZ0J0TDMxbHh4SHR1L3JQK25kYzk5ZDU3NHpaK0I0NXN5Y0FkUFlIbnRNR3RzeWcyekpZdWdXWTNjTEd0UnFadTVxWm1abVptWUd0Vmp2RzdFemQwVmxabFZYeXpOZTN4VnJaMlJXU2ZybFUxOS9ZMGZrUzdQTEQrZFdIczZ2UGxwWWZieTQ5bVJwL2NueStxT1ZqY2ZRNnVZVGFHM3JxZFRqOWUwbkxyUzI5ZGdnRncrdmJ6LzdtZHE0LzN4bDQxRjljOXZBK0p5enI5TC81dlQzZHpyU3Y1SCtzU3Y0OTI0OFc5dDRqa0xxMmNxbVhjc2J6d3hhV245cTBOemEwL24xWnhnTm1sMTk0a3d6cTQ5VlRhODhZVTB0UDJ
But the format I am looking for should contain "/", like the following (a random image I found):
/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMTEhUSEhMWFRUWGBcZGRgXFxcVFRgYFxUWFhcVFxgYHSggGBolGxcXITEhJSkrLi4uFx8zODMtNygtLisBCgoKDg0OGhAQGisdHx0tLS0tKy0tLS0tLSstLS0tLS0tLS0tKy0tLS0tLSstLS0tLSs3Ky0tKysrLSstKysrK//AABEIAMwAzAMBIgACEQEDEQH/xAAcAAABBAMBAAAAAAAAAAAAAAAGAgMEBQABBwj/xABCEAABAwIDBQUGAwYFBAMBAAABAgMRAAQSITEFBkFRYRMicYGRBzJCobHRFCPBUmKCk+HwM0NTctIVkqLxRGOyJP/
I don't know how to get the second format (containing the "/").
You're encoding it twice. Just do
let strBase64 = imageData?.base64EncodedStringWithOptions([])