swift JSON登录REST,带有post和get响应示例 [英] swift JSON login REST with post and get response example

查看:203
本文介绍了swift JSON登录REST,带有post和get响应示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

It's my first experience with REST in iOS development with swift. I couldn't find any working or straight (simple) example for doing what i need here.

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

I have a login backend (https://myaddress.com/rest/login), where I need to pass 2 params: login and password. When I pass good values (user exists in database) I get 2 variables as a result: token (string) and firstLogin (bool). So when I get those values I know that login is successful and I can log in into my app.

所以我求你举个例子(只是一个简单的函数)如何实现这一点。如果我得到工作代码示例,我将知道如何在我的应用程序中将其用于其他休息服务。我从我找到的教程中尝试了很多解决方案,但是其中任何一个都在为我工作..所以为了不浪费我的时间搜索我希望有经验的人向我展示实现这一目标的方法。

So I am begging you for an example (just a simple function) of how to achieve that. If I get working code example I will know how to use it for other rest services in my app. I tried many solutions from tutorials I found, but any of them was working for me.. So to not waste my time searching I would like someone experienced to show me the way to achieve that.

我不确定Alamofire是否如此优秀,我知道swift 4拥有自己的构建网络服务并与json合作。任何有效的解决方案都会很棒。

I am not sure if Alamofire is so good to use, I know that swift 4 has it's own build neetwork services and to work with json. Any solution that works would be great.

此外,附带问题 - 如果我更愿意使用Alamofire,我是否还需要使用swiftyJSON?或者它只是用于解析?

Also, side question - if I would prefer to use Alamofire, do I need to use swiftyJSON also? Or it's just for parsing?

推荐答案

如果你使用 URLSession 不喜欢在你的项目中导入 Alamofire 来执行一项简单的任务。

You can use URLSession if you don't like to import Alamofire in your Project to perform a simple task.

获取方法

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

POST METHOD

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

这篇关于swift JSON登录REST,带有post和get响应示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆