Last active
December 7, 2018 04:03
-
-
Save mtackes/510a40ac92f2a7bf75c3 to your computer and use it in GitHub Desktop.
An basic example of using an upload task with a completion handler.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Cocoa | |
| let session = NSURLSession.sharedSession() | |
| let request = NSURLRequest(URL: NSURL(string: "http://example.com")!) | |
| let dataToUpload = "Some Arbitrary Data".dataUsingEncoding(NSUTF8StringEncoding) | |
| let uploadTask = session.uploadTaskWithRequest(request, fromData: dataToUpload, | |
| completionHandler: { (responseData, response, error) in | |
| // Check on some response headers (if it's HTTP) | |
| if let httpResponse = response as? NSHTTPURLResponse { | |
| switch httpResponse.statusCode { | |
| case 200..<300: | |
| print("Success") | |
| case 400..<500: | |
| print("Request error") | |
| case 500..<600: | |
| print("Server error") | |
| case let otherCode: | |
| print("Other code: \(otherCode)") | |
| } | |
| } | |
| // Do something with the response data | |
| if let | |
| responseData = responseData, | |
| responseString = String(data: responseData, encoding: NSUTF8StringEncoding) { | |
| print("Server Response:") | |
| print(responseString) | |
| } | |
| // Do something with the error | |
| if let error = error { | |
| print(error.localizedDescription) | |
| } | |
| }) | |
| uploadTask.resume() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated one: