0

Hi guys I am trying to contact my Rest API and get the data. I am successful in doing that but I want the function to return the string that it obtained.

This is why code so far:

private func getPost(one: String, two: String, link: String) {
        let url = URL(string: link)!
        var request = URLRequest(url: url)
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "POST"
        let parameters: [String: Any] = [
            "parent" : one,
            "original": two
        ]
        request.httpBody = parameters.percentEncoded()
        var responseString = ""
        print("Sarcasm \(yourMessage) \(otherMessage) \(link)")
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data,
                  let response = response as? HTTPURLResponse,
                  error == nil else {                                              // check for fundamental networking error
                print("error", error ?? "Unknown error")
                return
            }
            
            guard (200 ... 299) ~= response.statusCode else {                    // check for http errors
                print("statusCode should be 2xx, but is \(response.statusCode)")
                print("response = \(response)")
                return
            }
            
            responseString = String(data: data, encoding: .utf8)!
            print("responseString = \(responseString)")
//            return responseString
        }
        task.resume()
    }

Where :

extension Dictionary {
    func percentEncoded() -> Data? {
        return map { key, value in
            let escapedKey = "\(key)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
            let escapedValue = "\(value)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
            return escapedKey + "=" + escapedValue
        }
        .joined(separator: "&")
        .data(using: .utf8)
    }
}

extension CharacterSet {
    static let urlQueryValueAllowed: CharacterSet = {
        let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
        let subDelimitersToEncode = "!$&'()*+,;="
        
        var allowed = CharacterSet.urlQueryAllowed
        allowed.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
        return allowed
    }()
}

All I want is this function (getPost) to return the response string that it obtains from the post request. However, I do not know what to do. I mean the application gets the response string from the post request but then I want to modify the function so that it returns it instead of printing it.

  • "I do not know what to do" meaning what!? Does the application crash? Does it show an error? Does it connect the server? What's the end side that is receiving data, a PHP script? – El Tomato Dec 30 '20 at 08:33
  • I mean the application gets the response string from the post request but then I want to modify the function so that it returns it instead of printing it. – Vaibhav Agrawal Dec 30 '20 at 08:38
  • 1
    Unrelated but it’s pointless to percent encode parameters in a POST request as they are transmitted as data bytes anyway. To return something form an asynchronous task look at https://stackoverflow.com/questions/25203556/returning-data-from-async-call-in-swift-function – vadian Dec 30 '20 at 09:00
  • @vadian I am still confused about how to do this. Can you please explain a bit more according to my situation. Thanks – Vaibhav Agrawal Dec 30 '20 at 09:12

0 Answers0