我正在尝试将旧的.js api调用转换为我的swift应用程序。在.js中,我必须发送带有api网址的查询,以决定要接收哪些字段。
例如“ https://api.myapi.com/planner?query=”和content.txt
content.txt
{
places(
ids:["ABC:StopPlace:8329","ABC:StopPlace:9237"]
) {
name
id
estimatedCalls(timeRange: 72100,numberOfDepartures: 20) {
realtime
realtimeState
expectedDepartureTime
predictionInaccurate
destinationDisplay {
frontText
}
}
}
}
现在我正在尝试:
func loadR(filename: String ) -> String {
let url = Bundle.main.url(forResource: filename,withExtension: "txt")!
let data = try! Data(contentsof: url)
let string = String(data: data,encoding: .utf8)!
print(string)
self.load(q: string)
return string
}
func load(q: String) {
var urlQ = "https://api.apisite.com/planner?query=" + q
let url = URL(string: urlQ)!
URLSession.shared.dataTask(with: url) {(data,resp,error) in
do {
if let d = data {
print(data)
/*
let decodedLists = try JSONDecoder().decode([Weather].self,from: d)
DispatchQueue.main.async {
self.metroTimes = decodedLists
}
*/
}else {
print("No Data")
}
} catch {
print ("Error")
print(error)
}
}.resume()
}
但是会引发错误: “致命错误:解开可选值时意外发现nil:”
将文件解析为url字符串的正确方法是什么?