-3

I have found learning swift to be more or less unbearable to do anything, something that would be done in a single line in Python becomes a whole task in swift.

I am trying to return the data from a http request and cannot find a single source that explains how. The only things I can find prints the data instead of returning it, either as a dictionary (from using JSONSerialization) or simply as a string.

let url = URL(string: "url")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
    if let error = error {
        print("error: \(error)")
    } else {
        if let response = response as? HTTPURLResponse {
            print("statusCode: \(response.statusCode)")
        }
        if let data = data, let dataString = String(data: data, encoding: .utf8) {
            print("data: \(dataString)")
        }
    }
}
task.resume()
adam
  • 51
  • 1
  • 6
  • How about https://stackoverflow.com/questions/25203556/returning-data-from-async-call-in-swift-function. But why do you want to *return* something? – vadian Dec 09 '19 at 05:10

1 Answers1

-1

func makePostRequest(){

let urlPath: String = "http://www.swiftdeveloperblog.com/http-post-example- script/"
var url: NSURL = NSURL(string: urlPath)!
var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)

request.HTTPMethod = "POST"
var stringPost="firstName=James&lastName=Bond" // Key and Value

let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)

request.timeoutInterval = 60
request.HTTPBody=data
request.HTTPShouldHandleCookies=false

let queue:NSOperationQueue = NSOperationQueue()

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
    var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
    let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary

     if (jsonResult != nil) {
        // Success
       println(jsonResult)

       let message = jsonResult["Message"] as! NSString

       println(message)
     }else {
        // Failed
        println("Failed")
    }

})

}

savan patel
  • 254
  • 1
  • 5