我正在构建一项调查,当用户回答问题时,我将答案附加到带有参数的 url 字符串,并向我的服务器发送 get 请求。因此,对于每个答案,都有一个由所选答案、时间戳和调查的唯一 ID 组成的记录。
我不确定最好的方法,但这是我到目前为止所拥有的。
我创建 url 和查询项目。
var urlComponents: URLComponents {
let resultID = surveyQuestions.resultId
print("\(String(describing: resultID))")
let resultResponseID = surveyQuestions.questions[surveyResultResponseId]
print("\(String(describing: resultResponseID))")
let questionIndex = questionNumbers
print("\(String(describing: questionIndex))")
var urlComponents = URLComponents(string: "My String URL")
urlComponents?.queryItems = [
URLQueryItem(name: "surveyResultsId", value: "\(String(describing: resultID))"),
URLQueryItem(name: "surveyResultsResponseId", value: "\(String(describing: resultResponseID))"),
URLQueryItem(name: "questions", value: "\(questionIndex)"),
URLQueryItem(name: "selectedAnswer", value: "\(storedAnswer)")
]
let url = urlComponents?.url
print(url!.absoluteString as Any)
return urlComponents!
}
然后我构建发送请求。
func sendRequest(_ url: String, parameters: [String: String], completion: @escaping ([String: Any]?, Error?) -> Void) {
var components = URLComponents(string: url)!
components.queryItems = parameters.map { (key, value) in
URLQueryItem(name: key, value: value)
}
components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
let request = URLRequest(url: components.url!)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, // is there data
let response = response as? HTTPURLResponse, // is there HTTP response
(200 ..< 300) ~= response.statusCode, // is statusCode 2XX
error == nil else { // was there no error, otherwise ...
completion(nil, error)
return
}
let responseObject = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
completion(responseObject, nil)
print("This is the \(responseObject!)")
}
task.resume()
}
最后,当按下答案时,我会调用发送请求。
@IBAction func answerPressed(_ sender: UIButton) {
if sender.tag == selectedAnswer {
questionNumbers += 1
}
storedAnswer = [sender.tag]
// storedAnswer.append(sender.tag)
print(storedAnswer)
sendRequest("\(urlComponents)", parameters: ["": ""]) { responseObject, error in
guard let responseObject = responseObject, error == nil else {
print(error ?? "Unknown error")
return
}
// use `responseObject` here
}
questionNumbers += 1
updateQuestion()
}
现在,当我运行它时,我会返回带有查询项的字符串,但是当我运行发送请求时,我会收到未知错误。我觉得好像我做错了什么。对于“在此处使用 responseObject”区域,我在其中放置了什么。我有点困惑。另外,当我调用发送请求时,我应该在参数值中输入什么。现在它们只是参数:[“”:“”]。我感觉好像我很亲近。任何帮助深表感谢。