What is the best way to split this String into two using Swift?
"https://apod.nasa.gov/apod/http://nusoft.fnal.gov/nova/public/img/FD-evt-echo.gif"
I only need the second part of url in the String. In this example, in this case I just need:
"http://nusoft.fnal.gov/nova/public/img/FD-evt-echo.gif"
let str = "https://apod.nasa.gov/apod/http://nusoft.fnal.gov/nova/public/img/FD-evt-echo.gif"
if let lastStr = str.components(separatedBy: "http").last
{
let result = "http" + lastStr
print(result)
}
Console Output: http://nusoft.fnal.gov/nova/public/img/FD-evt-echo.gif
Related
What is the best way to get the id value from this url:
URL(string: "urlScheme://search/:id=0001")
I've been trying to route this URL using a deep link request. However, my url routing solution JLRoutes shows the parameters as key = id and value = :id=0001.
I instead need the parameters to be key = id and value = "0001".
In an ideal world I would just be using a URL string like "urlScheme://search/0001" and not have any problem but the ":id=" part has to be in there. George's comment about converting the parameter to a URL in of itself and using .pathComponents.last does work, but I think a regex solution is probably going to scale better going forward.
The answer from #George should work fine, but two things struck me: you decided you wanted a regex solution, and to make this generic seemed to be asking for a recursive solution.
The below approach uses regex to identify up to the last /: delimiter, then has to do a bit of inelegant string handling to split it into the base string and the final pair of (key: value) params. I'd hoped to be able to write a regex that just matches those final parameters as that would be a far cleaner range to work with, but haven't managed it yet!
func paramsFrom(_ str: String) -> [String: String] {
guard let baseRange = str.range(of:#"^.+\/:"#, options: .regularExpression ) else { return [:] }
let base = String(str[baseRange].dropLast(2))
let params = str.replacingCharacters(in: baseRange, with: "").components(separatedBy: "=")
return [params.first! : params.last!].merging(paramsFrom(base)){(current, _) in current}
}
using this on your example string returns:
["id": "0001", "title": "256", "count": "100"]
EDIT:
Managed to dig out the old regex brain cells and match just the final pair of parameters. You could adapt the above to use the regex
(?<=\/:)[a-zA-Z0-9=]+$
and the have slightly cleaner string handling as the shortened base string becomes
String(str.dropLast(str[paramsRange].count))
If your URL is in the form of an actual URL query, e.g. urlScheme://search?id=0001, there is a nice way to do this.
With thanks to vadian, this is really simple. You can just do the following:
let components = URLComponents(string: "urlScheme://search?id=0001&a=2")!
let dict = components.queryItems?.reduce(into: [:]) { partialResult, queryItem in
partialResult[queryItem.name] = queryItem.value
}
Or a slightly more compact version for dict:
let dict = components.queryItems?.reduce(into: [:], { $0[$1.name] = $1.value })
Result from given input:
["id": "0001", "a": "2"]
If you must use the current URL form
You can replace the URL string, such as:
let urlStr = "urlScheme://search/:id=0001/:a=2"
let comps = urlStr.components(separatedBy: "/:")
let newUrl: String
if comps.count > 1 {
newUrl = "\(comps.first!)?\(comps.dropFirst().joined(separator: "&"))"
} else {
newUrl = urlStr
}
print(newUrl)
Prints: urlScheme://search?id=0001&a=2
Original answer (slightly modified)
If you have a URL with queries separated by /: you can use the following:
// Example with multiple queries
let url = URL(string: "urlScheme://search/:id=0001/:a=2")!
let queries = url.lastPathComponent.dropFirst().split(separator: "/:")
var dict = [String: String]()
for query in queries {
let splitQuery = query.split(separator: "=")
guard splitQuery.count == 2 else { continue }
let key = String(splitQuery.first!)
let value = String(splitQuery[1])
dict[key] = value
}
print(dict)
Result is same as before.
You can use next regex approach to enumerate parameters in your url path:
let urlString = "urlScheme://search/:id=0001" as NSString
let regex = try! NSRegularExpression(pattern: "([^:\\/]+)=([0-9]+)")
if let match = regex.matches(in: urlString as String, options: [], range: NSMakeRange(0, urlString.length)).first, match.numberOfRanges == 3 {
let key = urlString.substring(with: match.range(at: 1))
let value = urlString.substring(with: match.range(at: 2))
print(key, ":", value)
}
// Prints
id : 0001
A question I think pretty simple but I never had to do it in swift. it's pretty simple PHP but here I do not find my solution on the internet.
ask: I would like to add a variable in this chain of character. Instead of 123, I would need a variable.
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_123.json"
result = final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_VARAIBLE.json"
Can you give me the syntax in swift3 or direct me to a good tutorial.
You can create a string using string formatting.
String(format:"https://ozsqiqjf.preview.infomaniak.website/empdata_%d.json", variable)
let variable = 123
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_\(variable).json"
\(variable) is what you need
OR
use string formatting
let variable = 123
final let urlString = String(format:"https://ozsqiqjf.preview.infomaniak.website/empdata_%d.json", variable)
There is good documentation about Strings in Swift Language Guide. Your options are:
Concatenating Strings
let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_" + value + ".json"
String interpolation
let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_\(value).json"
Swift4 You can add a string in these ways:
var myString = "123" // Or VARAIBLE Here any string you pass!!
var urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_\(myString).json"
A simple way of doing it could be:
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_" + variablename + ".json"
You can also do it like this (a little more typesafe):
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_\(variablename).json"
Swift will read \(variablename) into the string automatically and accepts - among all things - integers.
let variable = 123
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_" + variable + ".json"
or
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_\(variable).json"
I have a string such as \home\var\path\uplaod\abc.png. Now I want to get data from uplaod onwards. Please suggest any function or code?
If path of image is not fixed or order of uplaod is not specific try like this.
let string = "\\home\\var\\path\\uplaod\\abc.png"
if let range = string.range(of: "uplaod") {
let imagePath = string.substring(from: range.lowerBound)
print(imagePath)
}
Output
uplaod\abc.png
let string = "\\home\\var\\path\\uplaod\\abc.png"
let parts = string.components(separatedBy: "\\")
parts // ["", "home", "var", "path", "uplaod", "abc.png"]
Any of the elements of this array you can get by its index.
parts[4..<parts.count].joined(separator: "\\") // "uplaod\\abc.png"
I am using Xcode7.3 with Swift2.2.
I want to append an Array in url request.For example my array like
[“jeevan”,”jeejo”]. I want to append this array with key(arrayKey) in url request like must be the following pattern
https://api.com/pre/ws/ch/roo?arrayKey=jeevan%2Cjeejo
How to solve this issue? Please help me
You need to use encode your URL instead of join Array with separator, but if you want to merge Array with URL you can try like this.
let str = ["jeevan","jeejo"]
let join = str.joinWithSeparator("%2C")
let url = "https://api.com/pre/ws/ch/roo?arrayKey=\(join)"
If you want to encode url encode this way.
let str = ["jeevan","jeejo"]
let join = str.joinWithSeparator(",")
let url = "https://api.com/pre/ws/ch/roo?arrayKey=\(join)"
let encoded = url.stringByAddingPercentEncodingWithAllowedCharacters(.URLFragmentAllowedCharacterSet())
Note : The reason I have used , is because %2C is encode for , you can confirm it here on W3School URL Encoding.
easy solution can be like this
var URIString = ""
for item in array {
URIString +=\(item)%2C
}
after subtract last 3 characters and make URL string
Simple code like this
var array: [String] = ["jeevan","jeejo"]
var myString = ""
for i in 0..<array.count {
myString += array[i]
if (i+1)<array.count { mystring+="%2C" }
}
Can give you result like this:
jeevan%2Cjeejo
This question already has answers here:
Finding index of character in Swift String
(33 answers)
Closed 6 years ago.
This sounds easy, but I am stumped. The syntax and functions of Range are very confusing to me.
I have a URL like this:
https://github.com/shakked/Command-for-Instagram/blob/master/Analytics%20Pro.md#global-best-time-to-post
I need to extract the part #global-best-time-to-post, essentially the # to the end of the string.
urlString.rangeOfString("#") returns Range
Then I tried doing this assuming that calling advanceBy(100) would just go to the end of the string but instead it crashes.
hashtag = urlString.substringWithRange(range.startIndex...range.endIndex.advancedBy(100))
Easiest and best way to do this is use NSURL, I included how to do it with split and rangeOfString:
import Foundation
let urlString = "https://github.com/shakked/Command-for-Instagram/blob/master/Analytics%20Pro.md#global-best-time-to-post"
// using NSURL - best option since it validates the URL
if let url = NSURL(string: urlString),
fragment = url.fragment {
print(fragment)
}
// output: "global-best-time-to-post"
// using split - pure Swift, no Foundation necessary
let split = urlString.characters.split("#")
if split.count > 1,
let fragment = split.last {
print(String(fragment))
}
// output: "global-best-time-to-post"
// using rangeofString - asked in the question
if let endOctothorpe = urlString.rangeOfString("#")?.endIndex {
// Note that I use the index of the end of the found Range
// and the index of the end of the urlString to form the
// Range of my string
let fragment = urlString[endOctothorpe..<urlString.endIndex]
print(fragment)
}
// output: "global-best-time-to-post"
You could also use substringFromIndex
let string = "https://github.com..."
if let range = string.rangeOfString("#") {
let substring = string.substringFromIndex(range.endIndex)
}
but I'd prefer the NSURL way.
use componentsSeparatedByString method
let url = "https://github.com/shakked/Command-for-Instagram/blob/master/Analytics%20Pro.md#global-best-time-to-post"
let splitArray = url.componentsSeparatedByString("#")
your required last text phrase (without # char) will be at the last index of the splitArray , you can concatenate the # with your phrase
var myPhrase = "#\(splitArray[splitArray.count-1])"
print(myPhrase)