ios - 使用 post 快速 JSON 登录 REST 并获取响应示例

标签 ios json rest alamofire swift4

这是我在 iOS 开发中使用 REST 的第一次体验。我在这里找不到任何工作或直接(简单)的例子来做我需要的事情。

我有一个登录后端 ( https://myaddress.com/rest/login ),我需要在其中传递 2 个参数:登录名和密码。当我传递良好的值(用户存在于数据库中)时,我得到 2 个变量:token(字符串)和 firstLogin(bool)。因此,当我获得这些值时,我知道登录成功并且我可以登录到我的应用程序。

因此,我请求您提供一个示例(只是一个简单的函数)来说明如何实现这一点。如果我得到有效的代码示例,我将知道如何将它用于我的应用程序中的其他休息服务。我从我找到的教程中尝试了很多解决方案,但它们中的任何一个都对我有用。所以为了不浪费我的时间进行搜索,我希望有经验的人向我展示实现该目标的方法。

我不确定 Alamofire 是否很好用,我知道 swift 4 有它自己的构建网络服务并且可以使用 json。任何可行的解决方案都会很棒。

此外,附带问题 - 如果我更喜欢使用 Alamofire,我还需要使用 swiftyJSON 吗?还是只是为了解析?

最佳答案

如果您不喜欢在您的项目中导入 Alamofire 来执行简单任务,您可以使用 URLSession

这里有一些方法:GET、POST、DELETE METHODS 和 tutorial

获取方法

func makeGetCall() {
  // Set up the URL request
  let todoEndpoint: String = "https://jsonplaceholder.typicode.com/todos/1"
  guard let url = URL(string: todoEndpoint) else {
    print("Error: cannot create URL")
    return
  }
  let urlRequest = URLRequest(url: url)

  // set up the session
  let config = URLSessionConfiguration.default
  let session = URLSession(configuration: config)

  // make the request
  let task = session.dataTask(with: urlRequest) {
    (data, response, error) in
    // check for any errors
    guard error == nil else {
      print("error calling GET on /todos/1")
      print(error!)
      return
    }
    // make sure we got data
    guard let responseData = data else {
      print("Error: did not receive data")
      return
    }
    // parse the result as JSON, since that's what the API provides
    do {
      guard let todo = try JSONSerialization.jsonObject(with: responseData, options: [])
        as? [String: Any] else {
          print("error trying to convert data to JSON")
          return
      }
      // now we have the todo
      // let's just print it to prove we can access it
      print("The todo is: " + todo.description)

      // the todo object is a dictionary
      // so we just access the title using the "title" key
      // so check for a title and print it if we have one
      guard let todoTitle = todo["title"] as? String else {
        print("Could not get todo title from JSON")
        return
      }
      print("The title is: " + todoTitle)
    } catch  {
      print("error trying to convert data to JSON")
      return
    }
  }
  task.resume()
}

发布方法

func makePostCall() {
  let todosEndpoint: String = "https://jsonplaceholder.typicode.com/todos"
  guard let todosURL = URL(string: todosEndpoint) else {
    print("Error: cannot create URL")
    return
  }
  var todosUrlRequest = URLRequest(url: todosURL)
  todosUrlRequest.httpMethod = "POST"
  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
    }

    // parse the result as JSON, since that's what the API provides
    do {
      guard let receivedTodo = try JSONSerialization.jsonObject(with: responseData,
        options: []) as? [String: Any] else {
          print("Could not get JSON from responseData as dictionary")
          return
      }
      print("The todo is: " + receivedTodo.description)

      guard let todoID = receivedTodo["id"] as? Int else {
        print("Could not get todoID as int from JSON")
        return
      }
      print("The ID is: \(todoID)")
    } catch  {
      print("error parsing response from POST on /todos")
      return
    }
  }
  task.resume()
}

删除方法

func makeDeleteCall() {
  let firstTodoEndpoint: String = "https://jsonplaceholder.typicode.com/todos/1"
  var firstTodoUrlRequest = URLRequest(url: URL(string: firstTodoEndpoint)!)
  firstTodoUrlRequest.httpMethod = "DELETE"

  let session = URLSession.shared

  let task = session.dataTask(with: firstTodoUrlRequest) {
    (data, response, error) in
    guard let _ = data else {
      print("error calling DELETE on /todos/1")
      return
    }
    print("DELETE ok")
  }
  task.resume()
}

关于ios - 使用 post 快速 JSON 登录 REST 并获取响应示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48285694/

相关文章:

PHP:foreach 循环与 array_merge 来创建 json 对象

java - WebSphere REST 服务错误 "FFDC Incident emitted"

ios - PanGesture 和一些基础数学

ios - 如何使用带有现有 UIPageViewController 的按钮以编程方式滑动 View

javascript - 如何从 PHP 后端接收 JSON 对象并将其转换为前端的 JavaScript 数组

rest - Glassfish 与 Tomcat 的 RESTful 服务对比

javascript - 类型 'any[]' (JSON) 上不存在 Angular2 属性

objective-c - 根据另一个字段的值设置文本字段的值

ios - 我怎样才能准确地知道哪个物体导致了我的崩溃?

objective-c - 操作无法完成。 ( cocoa 错误 : 3840.)