How to append something like ?id=1 to a NSMutableURLRequest
Asked Answered
D

1

7

I want to display the data from this URL: http://www.football-data.org/soccerseasons/351/fixtures?timeFrame=n14

My baseURL is let baseUrl = NSURL(string: "http://www.football-data.org")!,

so my request is let request = NSMutableURLRequest(URL: baseUrl.URLByAppendingPathComponent("soccerseasons/" + "\(league.id)" + "/fixtures?timeFrame=n14"))

But the ?timeFrame=n14 doesn't work.

Anyone knows how to solve this so I can display that data?

Dreamworld answered 16/11, 2014 at 12:58 Comment(0)
S
17

The problem is that the question mark in ?timeFrame=n14 is treated as part of the URL's path and therefore HTML-escaped as %3F. This should work:

let baseUrl = NSURL(string: "http://www.football-data.org")!
let url = NSURL(string: "soccerseasons/" + "\(league.id)" + "/fixtures?timeFrame=n14", relativeToURL:baseUrl)!
let request = NSMutableURLRequest(URL: url)

Alternatively, use NSURLComponents, which lets you build an URL successively from individual components (error checking omitted for brevity):

let urlComponents = NSURLComponents(string: "http://www.football-data.org")!
urlComponents.path = "/soccerseasons/" + "\(league.id)" + "/fixtures"
urlComponents.query = "timeFrame=n14"

let url = urlComponents.URL!
let request = NSMutableURLRequest(URL: url)

Update for Swift 3:

var urlComponents = URLComponents(string: "http://www.football-data.org")!
urlComponents.path = "/soccerseasons/" + "\(league.id)" + "/fixtures"
urlComponents.query = "timeFrame=n14"

let url = urlComponents.url!
var request = URLRequest(url: url)
Sidwohl answered 16/11, 2014 at 14:41 Comment(1)
Yes, that's the answer. Thank you very much!Dreamworld

© 2022 - 2024 — McMap. All rights reserved.