Den3243
Den3243

Reputation: 161

Swift URL query string get parameters

I'm using the OAuthSwift library to authenticate users of my app, but something doesn't seem to be working as it throws an error. After some debugging it seems to be going wrong on this line: parameters = url.query!.parametersFromQueryString()

It does have the url query string (set to url.query) but it somehow fails parsing the parametersFromQueryString(). Does someone else have this problem (with this library) and how did you solve it?

The "parametersFromQueryString" function can be found here: https://github.com/dongri/OAuthSwift/blob/1babc0f465144411c0dd9721271f239685ce83a9/OAuthSwift/String%2BOAuthSwift.swift

Upvotes: 1

Views: 3252

Answers (2)

Umair Ali
Umair Ali

Reputation: 836

Create an extension of URL class and paste this code:

import Foundation

extension URL {
public var parametersFromQueryString : [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
    }
}}

Now you can get the value of this calculated attribute from URL object by simply using:

url.parametersFromQueryString

Upvotes: 2

Shachar Silbert
Shachar Silbert

Reputation: 29

Have you checked that url.query returns anything? and that it is url decoded before/after calling url.query?

try looking at the answers here: URL decode in objective-c

If the method is looking for characters such as '?' or '=' and the URL is still encoded, it might not find them

Here is the same code as it should look like in swift:

let URLString = "http://sound17.mp3pk.com/indian/barfi/%5BSongs.PK%5D%20Barfi%20-%2001%20-%20Barfi!.mp3"
let URL = NSURL(string:url)
let filename = URL.path.lastPathComponent.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
//=> [Songs.PK] Barfi - 01 - Barfi!.mp3

Upvotes: 0

Related Questions