我想显示此网址中的数据:
http://www.football-data.org/soccerseasons/351/fixtures?timeFrame=n14
我的baseURL是let baseUrl = NSURL(string: "http://www.football-data.org")!
,
所以我的请求是let request = NSMutableURLRequest(URL: baseUrl.URLByAppendingPathComponent("soccerseasons/" + "\(league.id)" + "/fixtures?timeFrame=n14"))
但?timeFrame=n14
无效。
任何人都知道如何解决这个问题,以便我可以显示这些数据吗?
答案 0 :(得分:16)
问题是?timeFrame=n14
中的问号被视为网址的一部分
路径,因此HTML转义为%3F
。这应该有效:
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)
或者,使用NSURLComponents
,它允许您从各个组件连续构建URL(为简洁起见,省略了错误检查):
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)
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)