我想使用 JWT token 从 API 安全地提供我的数据。所以目前我已经在后端实现了安全性,并且每个 ajax 调用都在 header 中
url:"https://dataurl,
contentType : "application/json; charset=utf-8",
headers : TokenHeader(),
但现在我想发送相同的数据供 swift 开发的 IOS 应用程序使用。我不是 IOS 移动开发人员,当我研究他们如何进行其余调用时,我发现像这样的东西可以完成:
let todosEndpoint: String = "https://dataurl"
guard let todosURL = URL(string: todosEndpoint) else {
print("Error: cannot create URL")
return
}
var todosUrlRequest = URLRequest(url: todosURL)
todosUrlRequest.httpMethod = "GET"
let newTodo: [String: Any] = ["title": "My First todo", "completed": false, "userId": 1]
let jsonTodo: Data
do {
jsonTodo = try JSONSerialization.data(withJSONObject: newTodo, options: [])
todosUrlRequest.httpBody = jsonTodo
} catch {
print("Error: cannot create JSON from todo")
return
}
let session = URLSession.shared
let task = session.dataTask(with: todosUrlRequest) {
(data, response, error) in
guard error == nil else {
print("error calling POST on /todos/1")
print(error)
return
}
guard let responseData = data else {
print("Error: did not receive data")
return
}
所以现在我的问题就像我的网络应用程序中的 ajax 调用如何从移动应用程序端使用休息服务。感谢任何帮助?
最佳答案
我建议你使用这样的标题
let request = NSMutableURLRequest(url: NSURL(string: urlString)! as URL)
request.addValue("application/json",forHTTPHeaderField: "Content-Type")
request.addValue("application/json",forHTTPHeaderField: "Accept")
request.cachePolicy = .reloadIgnoringLocalCacheData
关于ios - 如何在 swift 中使用 header 完成 api 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43175328/