Split Url Query in Swift

Split URL query in Swift

You can get the key value pairs this way:

let str = "encodedMessage=PD94bWwgdmVyNlPg%3D%3D&signature=kcig33sdAOAr%2FYYGf5r4HGN"
let arr = str.components(separatedBy:"&")
var data = [String:Any]()
for row in arr {
let pairs = row.components(separatedBy:"=")
data[pairs[0]] = pairs[1]
}
let message = data["encodedMessage"]
let sig = data["signature"]

I am not sure if that's what you were looking for or not. If it is not, could you please clarify a bit further as to what you are looking for?

Swift - Parse a string which contains a URL

The query part of an URL can be parsed with URLComponents

let yourTargetUrl = URL(string:"http://www.foo.ir/baz/result_false.php?error=Canceled%20By%20User")!

var dict = [String:String]()
let components = URLComponents(url: yourTargetUrl, resolvingAgainstBaseURL: false)!
if let queryItems = components.queryItems {
for item in queryItems {
dict[item.name] = item.value!
}
}
print(dict)

Best way to parse URL string to get values for keys?

edit (June 2018): this answer is better. Apple added NSURLComponents in iOS 7.

I would create a dictionary, get an array of the key/value pairs with

NSMutableDictionary *queryStringDictionary = [[NSMutableDictionary alloc] init];
NSArray *urlComponents = [urlString componentsSeparatedByString:@"&"];

Then populate the dictionary :

for (NSString *keyValuePair in urlComponents)
{
NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
NSString *key = [[pairComponents firstObject] stringByRemovingPercentEncoding];
NSString *value = [[pairComponents lastObject] stringByRemovingPercentEncoding];

[queryStringDictionary setObject:value forKey:key];
}

You can then query with

[queryStringDictionary objectForKey:@"ad_eurl"];

This is untested, and you should probably do some more error tests.

How do I convert url.query to a dictionary in Swift?

Simple Extension

extension URL {
var queryDictionary: [String: String]? {
guard let query = self.query else { return nil}

var queryStrings = [String: String]()
for pair in query.components(separatedBy: "&") {

let key = pair.components(separatedBy: "=")[0]

let value = pair
.components(separatedBy:"=")[1]
.replacingOccurrences(of: "+", with: " ")
.removingPercentEncoding ?? ""

queryStrings[key] = value
}
return queryStrings
}
}

USAGE

let urlString = "http://www.youtube.com/video/4bL4FI1Gz6s?hl=it_IT&iv_logging_level=3&ad_flags=0&endscreen_module=http://s.ytimg.com/yt/swfbin/endscreen-vfl6o3XZn.swf&cid=241&cust_gender=1&avg_rating=4.82280613104"
let url = URL(string: urlString)
print(url!.queryDictionary ?? "NONE")

How to parse URL with # in Swift?

The problem you're running into is that # isn't part of the path but introducing a new component of the URL, stored in url.fragment. It's similar to if you had https://example.com/foo/?test=/bar. ?test= isn't a path component but the beginning of the query.

You have two approaches you can take.

If https://something.com/room/order/12345555/product/543333?is_correct=true and https://something.com/room/#/order/12345555/product/543333?is_correct=true can be used interchangeably, as in viewing either page in the browser will land you on the same page, you could have a sanitizing step in your process:

var rawUrl = ...
var sanitizedUrl = url.replacingOccurrences(of: "/#/", with: "/")
var url = URL(string: url)

How much sanitization you do depends on your application. It could be that you only want to do (of: "/room/#/", with: "/room/")

Another option, if you know your fragment will always look like a partial URL would be to pass the fragment into URL:

let url = URL(string: rawUrl)!
let fragmentUrl = URL(string: url.fragment!, relativeTo: url)!

let fullPathComponents = url.pathComponents + fragmentUrl.pathComponents[1...];
var query = fragmentUrl.query

The above approach yields: ["/", "room", "order", "12345555", "product", "543333"] for the joined URL.

Which approach and how much sanitization you do will depend on your use-case.

Get the value of URL Parameters

You can use the belowCode to get the param

func getQueryStringParameter(url: String, param: String) -> String? {
guard let url = URLComponents(string: url) else { return nil }
return url.queryItems?.first(where: { $0.name == param })?.value
}

Call the method like let test1 = getQueryStringParameter(url, param: "test1")

Other method with extension:

extension URL {
public var queryParameters: [String: String]? {
guard
let components = URLComponents(url: self, resolvingAgainstBaseURL: true),
let queryItems = components.queryItems else { return nil }
return queryItems.reduce(into: [String: String]()) { (result, item) in
result[item.name] = item.value
}
}
}

How to parse a url to get key and value

The answer you are referring to is outdated and has been updated accordingly by the writer himself. Apple added [URLQueryItem] in the URLComponent object.

Try this.

Swift

    let urlString = "https://www.example.com/product-detail?journey_id=123456&iswa=1"
var dict: [String : String] = [:]
if let urlComponents = URLComponents(string: urlString), let queryItems = urlComponents.queryItems {
for item in queryItems {
dict[item.name] = item.value
}
}
print("dict : \(dict)")

Objective - C

NSString *urlString = @"https://www.example.com/product-detail?journey_id=123456&iswa=1";
NSMutableDictionary *dict = [NSMutableDictionary dictionary];

NSURLComponents *urlComponents = [NSURLComponents componentsWithString:urlString];
NSArray *queryItems = [urlComponents queryItems];

for (NSURLQueryItem *item in queryItems) {
[dict setValue:item.value forKey:item.name];
}

NSLog(@"dict %@", dict);

iOS: parse a URL into segments

NSURL has a method pathComponents, which returns an array with all the different path components. That should help you get the integer part. To get the name I'd use the host method of the NSURL. The docs say, that it should work if the URL is properly formatted, might as well give it a try then.

All in all, no need to convert into a string, there seems to be plenty of methods to work out the components of the URL from the NSURL object itself.



Related Topics



Leave a reply



Submit