enum LocationManagerError: Error {
case authorizationDenied
case coordinateError
}
func requestLocation(completion: @escaping (_ coordinate: CLLocationCoordinate2D) -> ()) throws {
locationManager.delegate = self
guard CLLocationManager.locationServicesEnabled() else {
throw LocationManagerError.authorizationDenied
}
locationManager.requestWhenInUseAuthorization()
locationManager.requestLocation()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
guard let coordinate = locationManager.location?.coordinate else {
throw LocationManagerError.coordinateError
}
completion(coordinate)
}
do {
try locationManger.requestLocation(){ coordinate in
currentLocationViewModel.convertToAddress(latitude: coordinate.latitude, longtitude: coordinate.longitude, completion: {
let locationName = $0
fineDustViewModel.loadFineDust(latitude: coordinate.latitude, longtitude: coordinate.longitude, completion: {
let entry = simpleEntry(currentDate: currentDate,
locationName: locationName,
fineDust: $0.fineDust,
ultraFineDust: $0.ultraFineDust,
configuration: configuration)
let refreshDate = Calendar.current.date(byAdding: .minute, value: 30, to: currentDate)!
let timeline = Timeline(entries: [entry], policy: .after(refreshDate))
completion(timeline)
})
})
}
} catch {
let entry = simpleEntry(currentDate: currentDate,
locationName: "오류",
fineDust: fineDustViewModel.fineDust("-"),
ultraFineDust: fineDustViewModel.ultraFineDust("-"),
configuration: configuration)
let refreshDate = Calendar.current.date(byAdding: .second, value: 10, to: currentDate)!
let timeline = Timeline(entries: [entry], policy: .after(refreshDate))
completion(timeline)
}
}
현재 코드 블럭을 나가기 전에 꼭 실행되어야 하는 코드를 작성하여 코드가 블록을 어떻게 빠져나가던 꼭 마무리 해야 하는 작업을 수행하도록 하는 것을 말한다.
func test() {
defer {
print("실행 2")
}
print("실행 1")
}
// 실행 1
// 실행 2