【问题标题】:Connecting my iOS app to a Web Application using JSON and POST problems使用 JSON 和 POST 问题将我的 iOS 应用程序连接到 Web 应用程序
【发布时间】:2018-01-18 16:37:19
【问题描述】:

我是后端应用程序创建的新手,所以目前所有这些都非常令人困惑。我目前正在尝试允许我创建的 iOS 应用程序将详细信息保存到 Rails Web 应用程序的 PostgreSQL 数据库中。 Web 应用程序和数据库运行良好。我正在尝试使用 JSON 和 POST 请求与此函数中显示的 Web 应用程序进行通信:

    func connect(){  
    let baseUrl = URL(string: "URL_HERE")
    var request = URLRequest(url: baseUrl!)
    let session = URLSession.shared

    request.httpMethod = "POST"

    let stringPost = "name=test&surname=man"

    let data = stringPost.data(using: .utf8)!

    request.timeoutInterval = 60
    request.httpBody=data

    let task = session.dataTask(with: request, completionHandler: {data, URLResponse, Error -> Void in

        let err1: NSError? = nil

        do{
            let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)
        }
        catch{
            print(err1!)
            print("Error")
        }

    })
    task.resume()

}

我想要的只是将用户保存到数据库中。 每次执行此方法时都会引发错误。 这是我唯一的方法。我确定我错过了程序的一部分,但我很难找到它是什么。我什至不知道如何进一步了解引发错误的原因。

在这方面的任何帮助将不胜感激,我很茫然。

【问题讨论】:

  • 函数调用时打印出error nil和Error
  • @B-Brenan 您收到的错误是什么?您没有在任何地方设置 err1。
  • 我打印出 nil 并打印出错误,我假设是因为尝试失败?

标签: ruby-on-rails json swift postgresql http


【解决方案1】:

你遇到了什么错误?

在与您的 Web 服务 API 进行通信时,您可能需要查看Alamofire,它易于使用、为您完成大部分繁重的工作,并且拥有一个非常扎实的支持社区。

以下是一些使用 Alamofire 的示例,您必须填写一些空白,但这是一个开始。

这是我使用 Swift 3 使用 Alamofire 对用户进行身份验证的方法

 func authenticateAsync(email: String, password: String, completion: @escaping (_ token: String?, _ status: String?, _ error: String?, _ response: DataResponse<Any>) -> Void) {
          let accumooParameters = self.formatAuthenticationParameters(email: email, password: password)
          let dispatchQueue = DispatchQueue(label: "com.mysite.api-response-queue",
                                            qos: DispatchQoS.userInitiated,
                                            attributes: DispatchQueue.Attributes.concurrent)

          Alamofire.request(Globals.Accumoo.Urls.Authentication.authenticateUser,
                            method: HTTPMethod.post,
                            parameters: accumooParameters,
                            encoding: JSONEncoding.default,
                            headers: ["Content-Type":"application/json; charset=UTF-8"])
             .validate(statusCode: 200..<300)
             .responseJSON(queue: dispatchQueue, options: JSONSerialization.ReadingOptions.allowFragments, completionHandler: {
                (response: DataResponse<Any>) in
                switch response.result {
                case .success(let data):
                   let json:JSON = JSON(data)
                   print(json.rawString()!)
                   let result = self.getAuthenticationResult(json: json)
                   completion(result.token, result.status, result.error, response)
                case .failure(let error):
                   completion("", String(describing: response.response?.statusCode ?? 0), String(error._code), response)
                }
             })
       }

internal func formatAuthenticationParameters(email: String, password: String) -> [String : Any]? {
      return ["email" : email, "password" : password]
   }

   internal func getAuthenticationResult(json: JSON) -> (token: String?, status: String?, error: String?) {
      let token = json["token"].string
      let status = json["status"].string
      let error = json["error"].string
      return getAuthenticationResult(token: token, status: status, error: error)
   }

   internal func getAuthenticationResult(token: String?, status: String?, error: String?) -> (token: String?, status: String?, error: String?) {
      return (token: token, status: status, error: error)
   }

这是我使用 Alamofire 在同一个应用程序中使用 Swift 3 发布经过身份验证的请求的方法

     // Update full name
   func updateFullName(with accessToken: String, fullName: String, completion: @escaping (DataResponse<Any>) -> Void) {
      let url = "https://api-mysite.herokuapp.com/mysite/users/update_user/"

      let params =  ["user" : ["full_name" : fullName]]

      put(with: accessToken, url: url, params: params, completion: { (dataResponse: DataResponse<Any>) in
         completion(dataResponse)
      })
   }

    // Post authenticated
       internal func post(with accessToken: String, url: String, params: [String : Any], completion: @escaping (DataResponse<Any>) -> Void) {
          let dispatchQueue = DispatchQueue(label: "com.mysite.api-response-queue",
                                            qos: DispatchQoS.userInitiated,
                                            attributes: DispatchQueue.Attributes.concurrent)
          Alamofire.request(url,
                            method: HTTPMethod.post,
                            parameters: params,
                            encoding: JSONEncoding.default,
                            headers: ["Content-Type" : "application/json; charset=UTF-8; version=1",
                            "Authorization" : accessToken])
             .validate(statusCode: 200..<300)
             .validate(contentType: ["application/json"])
             .responseJSON(
                queue: dispatchQueue,
                options: JSONSerialization.ReadingOptions.allowFragments,
                completionHandler: { (response: DataResponse<Any>) in completion(response) }
          )
       }

祝你好运。

【讨论】:

  • 感谢您的回答。这是我的必修项目,所以我需要以某种方式解决这个问题。问题是,rails web 应用程序已经功能齐全,并且可以与现有的 android 应用程序一起使用,我只需要制作一个在 web 应用程序上运行的 iOS 客户端。我知道这不是一个简单的项目,但我只需要一些正确方向的指示。
  • @B-Brennan,如果是这样的话,我的回答仍然适用于使用 Alamofire。您还需要查看 Rails 应用程序正在使用什么身份验证并对此进行说明,否则,您的所有请求都将失败。我将发布一个如何使用 Alamofire 调用 Web 服务的示例,但也有很多示例可以这样做。
  • 非常感谢。有没有一种简单的方法可以检查 rails 应用程序正在使用什么身份验证?
  • @B-Brennan 我想它必须是基于令牌的,实际上没有任何其他可行的选择,请问维护 rails 应用程序的家伙/小伙子。很可能您必须先进行身份验证,然后取回身份验证令牌。然后,您必须在对服务器的所有后续调用中使用该身份验证令牌来验证每个请求。身份验证令牌通常在请求的标头中传递。
  • 好的,我可以确定。我了解您所解释的程序,但是您知道网上有什么地方可以让我了解有关它的实施的更多信息吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-07
  • 1970-01-01
  • 1970-01-01
  • 2014-04-23
  • 2019-07-19
  • 2018-05-08
相关资源
最近更新 更多