简体   繁体   English

如何通过头快速完成API调用

[英]How api calls are done with headers in swift

I want to securely provide my data from the API using JWT token.So Currently I have implemented security in the backend and each ajax call eith the header 我想使用JWT令牌从API安全地提供数据。因此,目前我已经在后端实现了安全性,并且每个ajax调用都使用了标头

url:"https://dataurl,
        contentType : "application/json; charset=utf-8",
        headers : TokenHeader(),

But now I want to send the same data to be consumed by an IOS App which is developed in swift.I am not a IOS mobile developer and when I look into how they make the rest calls I found that something like this can be done: 但是现在我想发送相同的数据以供迅速开发的IOS App使用。我不是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
  }

So now my question is like ajax call in my web app how to consume rest service from the mobile app side.Any help is appreciated? 所以现在我的问题就像我的Web应用程序中的ajax调用一样,如何从移动应用程序端使用其余服务。

I suggest you to use headers like this 我建议您使用这样的标题

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

您想要类似的东西(取决于您需要发送的标头值):

todosUrlRequest.setValue("token value", forHTTPHeaderField: "Authorization")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM