Skip to content

Instantly share code, notes, and snippets.

@nhathm
Created April 24, 2017 07:37
Show Gist options
  • Select an option

  • Save nhathm/2f542988040d14359880f696bcf63350 to your computer and use it in GitHub Desktop.

Select an option

Save nhathm/2f542988040d14359880f696bcf63350 to your computer and use it in GitHub Desktop.
Sample about get data from server, this case will be failed because not using @escaping
//: Playground - noun: a place where people can play
// nhathm01247@gmail.com
import Foundation
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
class ServerConnection: NSObject {
let defaultSession = URLSession(configuration: URLSessionConfiguration.default)
var dataTask: URLSessionDataTask?
func getDataFromServer(url: String, completion: (String?) -> ()) {
let url: URL = URL(string: url)!
dataTask = defaultSession.dataTask(with: url) { data, response, error in
if let error = error {
print(error.localizedDescription)
completion(nil)
} else if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode == 200 {
completion("Sucess get data from server")
} else {
print("\(httpResponse.statusCode)")
completion(nil)
}
}
}
dataTask?.resume()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment