助手

时间:2017-03-28 21:37:31

标签: ios iphone swift macos rest

我正在研究swift 3应用程序,并希望使用REST API构建登录系统。首先,我想要一种方法将数据发布到带有参数的服务器(PHP + MYSQL),所以我找到了这篇文章。

HTTP Request in Swift with POST method

现在我想把这个代码作为助手放在一个方法中,这样我就可以在app的任何地方使用这个方法。因此遵循这种方式:

Where to put reusable functions in IOS Swift?

目前的代码如下:

import Foundation

class Helper {


static func postData(resource: String, params: [String: String]) -> [String:String] {

    var request = URLRequest(url: URL(string: "http://localsite.dev/api/\(resource)")!)
    request.httpMethod = "POST"

    var qryString: String = "?key=abcd"
    for (paramKey, paramVal) in params {
        qryString = qryString.appending("&\(paramKey)=\(paramVal)")
    }

    request.httpBody = qryString.data(using: .utf8)

    let task = URLSession.shared.dataTask(with: request) { data, response, error in

        guard let data = data, error == nil else {
            print("Error")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
            print("Error on HTTP")
            return
        }

        let responseString = String(data: data, encoding: .utf8)
        print("success and here is returned data \(responseString)")
    }

    task.resume()

    return ["data" : "some data"]

}
}

使用

调用此方法
let loginDetails: [String: String] = ["email": emailTxt.text!, "pass": passTxt.text!]
Helper.postData(resource: "login", params: loginDetails)

在上面的方法而不是打印数据我想按照以下4个条件返回数据。

1.如果请求数据出错,那么我想以

的形式返回
[“status”: false, “message”: “Something wrong with request”]

2.如果HTTP请求出错

[“status”: false, “message”: “Resource not found”]

3.如果登录失败

[“status”: false, “message”: “Wrong login details”]

4.如果登录成功

[“status”: true, “message”: “Login success”]

1 个答案:

答案 0 :(得分:0)

如果您想使用第三方库处理HTTP请求,我强烈建议Alamofire

当我想处理HTTP请求时,我通常会创建一个单例类:

class HttpRequestHelper {
   static let shared = HttpRequestHelper()

   func post(to url: URL, params: [String: String], headers: [String: String], completion: (Bool, String) -> ()){
         //Make the http request
         //if u got a successful response 
         // parse it to JSON and return it via completion handle
         completion(true, message)
         //if response is not successful
         completion(false, message)

   }

}

你可以在任何地方使用它:

class AnotherClass: UIViewController {
    HttpRequestHelper.shared.post(to: url, params: [:], header: [:], 
    completion:{
        success, message in 
          print(success)
          print(message)
    })
}

对于POST方法更可重用而不仅仅是特定于端点,我通常将完成处理程序params作为Bool,JSON。然后我从我调用方法的任何地方处理JSON响应。

哦,我使用SwiftyJson来解析json,它是最简单的。