How to add something like: id = 1 in NSMutableURLRequest

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

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

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

But ?timeFrame=n14 does not work.

Does anyone know how to solve this so that I can display this data?

+6
source share
1 answer

The problem is that the question mark in ?timeFrame=n14 considered as part of the URL 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 allows you to consistently create a URL from individual components (errors are 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) 
+14
source

Source: https://habr.com/ru/post/978254/


All Articles