0

I am working on swift 3 application and want to build login system using REST API. First I wanted a way to post data to server (PHP + MYSQL) with parameters so I found this post.

HTTP Request in Swift with POST method

Now I wanted place this code in a method as helper so I can utilise this method from anywhere in app. Hence followed this way:

Where to put reusable functions in IOS Swift?

Current code is as follow:

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"]

}
}

Call this using

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

In above method rather then printing data I want to return data as per below 4 conditions.

1.If error in request data then I want to return as

[“status”: false, “message”: “Something wrong with request”]

2.If error in HTTP request

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

3.If login fail

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

4.If login success

[“status”: true, “message”: “Login success”]
Community
  • 1
  • 1
VK321
  • 5,768
  • 3
  • 44
  • 47
  • You will need to pass a completion handler closure to your function and have the completion handler of the task invoke that handler to get the values back to your caller – Paulw11 Mar 28 '17 at 21:53
  • Hi again @Paulw11.. Could you please give me example? Sorry bit new to iphone development and swift. – VK321 Mar 28 '17 at 21:55

1 Answers1

0

If you want to use a third party library for handling HTTP request, I strongly recommend Alamofire.

When I wanna handle HTTP requests I usually create a singleton class:

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)

   }

}

And you can use it everywhere:

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

To the POST method more reusable and not just specific to an endpoint, I usually make the completion handler params as Bool, JSON. And then I handle the JSON response from wherever I call the method.

Oh and I use SwiftyJson to parse json, it's the simplest.

Shawerma
  • 171
  • 1
  • 4
  • 12
  • Can you give me example on my code.. when i replace print message with completion(true, message) i get error. – VK321 Mar 29 '17 at 19:09