This calls an asynchronous function that uses the block / close handler of completion. Thus, you need to use the completion handler template in your own code. This consists in changing the type of the returned method to Void and adding a new completionHandler closure that will be called when the asynchronous call is made:
func post(url: String, info: String, completionHandler: (NSString?, NSError?) -> ()) { let URL = NSURL(string: url)! let request = NSMutableURLRequest(URL:URL) request.HTTPMethod = "POST" let bodyData = info request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding); NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { response, data, error in guard data != nil else { completionHandler(nil, error) return } completionHandler(NSString(data: data!, encoding: NSUTF8StringEncoding), nil) } }
Or, since NSURLConnection now officially deprecated, it is better to use NSURLSession :
func post(url: String, info: String, completionHandler: (NSString?, NSError?) -> ()) -> NSURLSessionTask { let URL = NSURL(string: url)! let request = NSMutableURLRequest(URL:URL) request.HTTPMethod = "POST" let bodyData = info request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding); let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in dispatch_async(dispatch_get_main_queue()) { guard data != nil else { completionHandler(nil, error) return } completionHandler(NSString(data: data!, encoding: NSUTF8StringEncoding), nil) } } task.resume() return task }
And you call it that:
post(url, info: info) { responseString, error in guard responseString != nil else { print(error) return }
Note. To make it simple, I used the syntax of trailing closure (see the section "Trailing closure" in Swift Programming: Closures ), but I hope this illustrates the idea: you cannot immediately return the result of the asynchronous method, so provide closure of the completion handler. which will be called when the asynchronous method is executed.