API (Application Programming Interface) is a set of commands, function, protocols, objects that programmers can use to create software or interact with an external system.
<aside> 💡 내 앱과 웹서버와의 통신 (request, response)을 어떻게 할까?
</aside>
func performRequest(urlString: String) {
//1. create a url
if let url = URL(string: urlString) {
//2. creata a url session
let session = URLSession(configuration: .default)
//3. give the session a task
let task = session.dataTask(with: url, completionHandler: handle(data:response:error:))
//handler는 비동기처리를 위한 함수.
//4. start the task
print("start the task")
task.resume()
}
}
func handle(data: Data?, response: URLResponse?, error: Error?) -> Void {
if error != nil {
print(error!)
return
}
print("비동기처리 핸들러 데이터가 오기전까지 실행안됨")
if let safeData = data {
let dataString = String(data: safeData, encoding: .utf8)
print(dataString)
}
}
https://developer.apple.com/documentation/foundation/urlsession
JSON (JavaScript Object Notation)
we initialize swift object with either a struct or a class