Getting query string parameters from url in the UIWebView in Swift? - ios

my question is pretty straight forward. Can someone please show me how to get the query string parameters in a url received by the UIWebView. It is pretty easy in objective c, but I need some help in swift as i'm new to the language. Thanks in advance.

In the NSURL class exists the .query property which returns the string of everything after the ? in the url in form:
http://www.example.com/index.php?key1=value1&key2=value2
in this example using the code:
var url: NSURL = NSURL(string: "http://www.example.com/index.php?key1=value1&key2=value2")
println(url.query) // Prints: Optional("key1=value1&key2=value2")
More information in the documentation
As far as getting the url from the uiwebview, you could use something along the lines of:
let url: NSURL = someWebView.NSURLRequest.URL

To make it a bit easier to get the value of a particular parameter you expect, you can use URLComponents which will parse out the query string parameters for you.
For example, if we want the value of the query string parameter key2 in this URL:
"https://www.example.com/path/to/resource?key1=value1&key2=value2"
We can create a URLComponents struct, then filter for the query item which matches the name, take the first one, and print its value:
let url = URL(string: "https://www.example.com/path/to/resource?key1=value1&key2=value2")
if let url = url,
let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
let parameterWeWant = urlComponents.queryItems?.filter({ $0.name == "key2" }).first
print(parameterWeWant?.value ?? "")
}
The key (!) thing is that urlComponents.queryItems gives us this array of QueryItem structs back, which gives us an easier way to filter the parameters and get the value of the parameter we're looking for.
▿ Optional([key1=value1, key2=value2])
▿ some: 2 elements
▿ key1=value1
- name: "key1"
▿ value: Optional("value1")
- some: "value1"
▿ key2=value2
- name: "key2"
▿ value: Optional("value2")
- some: "value2"

We can parse the Url params with this method,
func getParameterFrom(url: String, param: String) -> String? {
guard let url = URLComponents(string: url) else { return nil }
return url.queryItems?.first(where: { $0.name == param })?.value
}
let url = "http://www.example.com/index.php?key1=value1&key2=value2"
let key1 = self.getParameterFrom(url: url, param: "key1")
print("\(key1)") // value1

Related

Get correct parameter value from URL in "/:id=" format using regex

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

Swift: Get all key value pairs from a String

I have a String which has many key value pairs appended by a & sign. i.e: params = key1=Hello&key2=Hello World&key3=Hi Hello
Is there a way to extract the values just by passing the keys present in the string? For example I want to extract the value of key1, key2, key3.
let string = "key1=Hello&key2=Hello World&key3=Hi Hello"
let components = string.components(separatedBy: "&")
var dictionary: [String : String] = [:]
for component in components{
let pair = component.components(separatedBy: "=")
dictionary[pair[0]] = pair[1]
}
And in dictionary you will get your key-value pairs.
You can use URLComponents and URLQueryItem anyway by creating a dummy URL
let params = "key1=Hello&key2=Hello World&key3=Hi Hello"
if let components = URLComponents(string: "http://dummy.com/path?" + params.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!),
let queryItems = components.queryItems {
let arrayOfValues = queryItems.flatMap{ $0.value }
print(arrayOfValues)
}
see also Best way to parse URL string to get values for keys?
let params = "key1=Hello&key2=Hello World&key3=Hi Hello"
let sepparated = params.components(separatedBy: CharacterSet(charactersIn: "&="))
let keys = sepparated.enumerated().filter{$0.0 % 2 == 0}
print (keys) // [(offset: 0, element: "key1"), (offset: 2, element: "key2"), (offset: 4, element: "key3")]

The '#' char gets converted to %23 causing the GET Request to fail

I am a new Swift developer using Swift 3 developing an iOS app. I need to make a URL Request to get some data from the web. That URL contains a # character.
I use URLComponents with URLQueryItems to build the request URL. During this process the # char gets converted to %23 which I think is valid utf8 encoding. Unfortunately, this causes the GET to fail.
To test I pasted the URL into my browser and changed %23 back to # and it worked just fine.
How can I fix this so it does not change # to URL. I did find a post from a couple years ago but it was using old framework items so it does not apply to me.
Below is the playground I made to illustrate and test this.
// ------------------------------------------------------------------
//: Playground - TestBuildURLWithParameters
//
// I am using this playground to build the proper
// URL for the GET request to get the detailed
// rtesults for a specific athlete where the "Key"
// is their Bib Nbr. If the GET cant find the specific
// Atlete with that URL it redirects you to the list
// of athlete results (which is no go to me in this case)
//
// Currently, there is a big "gotcha". In building the URL
// using component and query items, the foundation classes
// replace the '#' sign in the URL with the %23 which represents
// the pound sign. Unfortunately, the causes the GET to fail
// and redirects to athlete list which is not helpful
// I am still trying to figure out how to FORCE it to keep
// the '#" character in the URL so it will work
//
// ------------------------------------------------------------------
import Foundation
import UIKit
let baseURLString = "http://www.ironman.com/triathlon/events/americas/ironman-70.3/augusta/results.aspx"
let rd = "20150927"
let race = "augusta70.3"
let bibID = "93"
var detail = "1#axzz4FGGcjBOn"
print("Detail w/o unicocde: \(detail)")
detail = "1\u{0023}axzz4FGGcjBOn"
print("Detail with unicocde: \(detail)")
var components = URLComponents(string: baseURLString)!
var queryItems: [URLQueryItem] = [] // All Items after the "?"
let baseParams =
[
"rd": rd,
"race": race,
"bidID": bibID, // Note: HTML mispelled bib with bid so "bidID" is the URL search
"detail": detail
]
for (key, value) in baseParams
{
let item = URLQueryItem(name: key, value: value)
queryItems.append(item)
}
components.queryItems = queryItems // what does this look like
print("components: \(components)") // see it
It is not a good way to include fragment part of URL into query items.
Try this:
import Foundation
let baseURLString = "http://www.ironman.com/triathlon/events/americas/ironman-70.3/augusta/results.aspx"
let rd = "20150927"
let race = "augusta70.3"
let bibID = "93"
var detail = "1"
//# split the last query item and the fragment
let fragment = "axzz4FGGcjBOn"
var components = URLComponents(string: baseURLString)!
var queryItems: [URLQueryItem] = []
let baseParams =
[
"rd": rd,
"race": race,
"bidID": bibID,
"detail": detail
]
for (key, value) in baseParams
{
let item = URLQueryItem(name: key, value: value)
queryItems.append(item)
}
components.queryItems = queryItems
components.fragment = fragment
print("components: \(components)")
If you need you can choose the character that will receive the encoding.
In the charactersIn: you put all characters you want to encode.
Then you use the .inverted so all the others characters will go normal like this:
let customAllowedSet = NSCharacterSet(charactersIn:"=\"%/<>?#\\^`{|}").inverted
let encondedString = originalString.addingPercentEncoding(withAllowedCharacters: customAllowedSet)
print("enconded string: \(encondedString)")
Encode your parameters and then add it to URL, this will encode # before hitting API and you'll get desired result.
To encode parameters, you can use below code.
var parameterString = "your parameter string"
var encodedString = parameterString .addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
print(encodedString !)
I did get an answer via email from a friend that works for now. Basically, I added the query items manually to the URL using the URL extension below so it didn't monkey with the '#' char:
extension URL {
func appendingNonEscapedQueryItems(_ queryItems: [URLQueryItem]) -> URL {
let url = self
var urlString = url.absoluteString
for queryItem in queryItems {
let queryName = queryItem.name
guard let queryValue = queryItem.value else {
continue
}
let query = queryName + "=" + queryValue
if queryItem == queryItems.first {
urlString = urlString + "?" + query
}
else
{
urlString = urlString + "&" + query
}
}
return URL(string: urlString)!
}
}
...
let requestURL = components.url!.appendingNonEscapedQueryItems(queryItems)
print("URL \(requestURL)")

How to append an array in URL request type GET in Swift?

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

Swift dictionary map - init in closure

I have Swift dictionary:
private var params = [String : AnyObject]()
This contains query items like:
"lat" = "40"
"lon" = "100"
I would like to map this dictionary to NSURLQueryItem array. I want to make it "swifty":
params.map{NSURLQueryItem.init}
But I get an error. Even if I change the map to be [String:String?]. I know I can do something like this elegant one-liner. Can anybody tell how?
You just need to add a failable initializer to NSURLQueryItem that receives a tuple like this (String, AnyObject)
extension NSURLQueryItem {
convenience init?(tuple: (String, AnyObject)) {
guard let value = tuple.1 as? String else { return nil }
self.init(name: tuple.0, value: value)
}
}
That's it!
let params: [String:AnyObject] = ["lat": "40", "lon": "100"]
let queryItems = params.flatMap(NSURLQueryItem.init)
Does your value for the dictionary need to be an optional? In a dictionary, when you assign its key as nil, the entry is deleted.
var params = [String:String?]()
params["lat"] = "40"
params["lon"] = "100"
params["key"] = "hey"
print(params) //result: ["lat": Optional("40"), "lon": Optional("100"), "key": Optional("hey")]
params["key"] = nil
print(params) //result: ["lat": Optional("40"), "lon": Optional("100")]
I suggest using a non optional-value dictionary. I have successfully written the code below:
import UIKit
var params = [String:String]()
params["lat"] = "40"
params["lon"] = "100"
let nsurl = params.map() {NSURLQueryItem.init(name: $0, value: $1)}
print(nsurl)
//Result:
//[<NSURLQueryItem 0x7f8252d29730> {name = lat, value = 40}, <NSURLQueryItem 0x7f8252d29700> {name = lon, value = 100}]
I hope this helps
To you can create one expression like this:
(1...100).map(String.init)
The class has to support it, the String has one initializer with the following signature:
public init(stringInterpolationSegment expr: Int)
With allow it to you use the String.init referred as Int -> String.
But in your case the NSURLQueryItem has not the desired initializer, so the more close you can do it is using map like in the conventional way and passing the parameters to the init of the class NSURLQueryItem like in this way:
let listMapped = params.map { NSURLQueryItem(name: $0.0, value: $0.1 as? String) }
I hope this help you.
I looked at What's the cleanest way of applying map() to a dictionary in Swift? and came up with these two answers:
var params = ["lat": "40", "lon":"100"]
var p:[NSURLQueryItem] = []
var result1 = params.map { (key, value) in p.append(NSURLQueryItem(name:key, value:value)) } // version 1
var result2 = params.reduce([NSURLQueryItem]()) { $0 + [NSURLQueryItem(name:$1.0, value:$1.1)] } // version 2
In version 1, the parameter passed by map() is a (String, String) tuple. In version 2, the parameters passed by reduce() are [NSURLQueryItem] and a (String, String) tuple
Firstly, the the block or closure you're providing to the map function isn't quite right. Blocks are basically nameless functions, they take some number of parameters and return some type. If we were to be verbose, a solution would look something like this:
params.map { (a: (String, String)) -> NSURLQueryItem in
return NSURLQueryItem(name: a.0, value: a.1)
}
However we can simplify this bit of code. The dictionary is [String : String] so it can be inferred that the map function will take a (String, String) as a parameter, so we don't need to write that explicitly.
Swift also allows $n to refer to the nth element of a tuple parameter. Since we only have 1 parameter, $0 will refer to the first element of the first parameter.
The return type of the block can also be inferred, since we're creating a NSURLQueryItem, meaning we don't need to specify that either. This means we also don't need to write return in the block, we can just create the object.
Lastly, you should not call NSURLQueryItem.init() to create a new NSURLQueryItem, you should instead just say NSURLQueryItem().
Here's the minimal solution:
params.map { NSURLQueryItem(name: $0, value: $1) }

Resources