当前位置: 首页 > 面试题库 >

使用发布和获取响应示例的快速JSON登录REST

越飞语
2023-03-14
问题内容

这是我第一次在iOS开发中快速使用REST的经验。我在这里找不到我需要的任何有效或简单的示例。

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

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

我不确定Alamofire是否能很好地使用,我知道swift 4拥有自己的构建neetwork服务并可以与json一起使用。任何可行的解决方案都会很棒。

另外,还有一个问题-如果我更喜欢使用Alamofire,是否还需要使用swiftyJSON?还是仅用于解析?


问题答案:

URLSession如果您不想导入Alamofire项目,则可以使用它来执行简单的任务。

这是一些方法:GET,POST,DELETE方法和教程

获取方法

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()
}


 类似资料:
  • 另外,附带问题-如果我更喜欢使用Alamofire,我是否也需要使用swiftyJSON?还是只是为了解析?

  • 问题内容: 我有一个特定的Web服务,期望将JSON作为发布内容,并将向后吐出XML。我正在对所有网络通话使用Retrofit。这是我使用XML转换器设置Retrofit适配器的方式: 如您所见,我没有使用Gson转换器。我如何设法发布任何JSON?谢谢! 问题答案: 创建自定义。这将使用不同的转换器进行序列化和反序列化。 用法:

  • 当我构建我的应用程序并尝试它时,没有任何错误,但当我在google play store上发布我的应用程序并尝试登录Facebook时,它会给我一个错误。这个错误是一个错误的散列键,因为散列键发生了变化(我得到了sign应用程序的散列键,通过许多方式给了我相同的has键,工作正常)这是第一个问题。 我的第二个问题是当尝试使用gmail登录(谷歌登录)获取字段错误。 (您有错误的OAuth2相关配置

  • 问题内容: 我是Node开发的新手,我正在尝试使用具有JSON响应的RESTful协议进行服务器端API调用。我已经阅读了API文档和本SO帖子。 我试图从轨道总线中提取的API并以JSON输出返回数据。我对如何使用实际URL中的所有参数和选项发出HTTP GET请求感到困惑。甚至可以通过浏览器或使用“ curl”命令来访问API及其响应。http://developer.cumtd.com/ap

  • 问题内容: 已关闭 。这个问题需要更加集中。它当前不接受答案。 想改善这个问题吗? 更新问题,使其仅通过编辑此帖子来关注一个问题。 2年前关闭。 改善这个问题 我在一个支持全国性网络上许多不同站点的大型组织中工作。我们的供应商为我们在每个站点使用的硬件提供诊断工具。诊断和报告可通过Telnet访问。 问题是我们想同时监视 所有 站点,当前我们只能一次(通过telnet)一次检查它们。 我已经构建了

  • 在这个声明的响应对象中,使用并使用检索响应数据,在此期间,甚至需要获取id的大小或长度,甚至需要获取标签数组的详细信息。 JSON响应: 尝试了以下方法: 或 请指导如何获得尺寸/长度。