Search code examples
iosswift

Swift: Escaping closure captures non-escaping parameter 'onCompletion'


I have a problem with my swift. I am trying to send an API request and then retrieve data but I get the following error message:

"Swift: Escaping closure captures non-escaping parameter 'onCompletion'".

Does anyone know how I can solve this? Code:

typealias ServiceResponse = (JSON, NSError?) -> Void

class RestApiManager: NSObject {
    static let sharedInstance = RestApiManager()
    
    let baseURL = "http://api.randomuser.me/"
    
    func getRandomUser(onCompletion : (JSON) -> Void) {
        makeHTTPGetRequest(path: baseURL, onCompletion: { json, err -> Void in
            onCompletion(json)
        })
    }
    
    func makeHTTPGetRequest(path: String, onCompletion: ServiceResponse) {
        let request = NSMutableURLRequest(url : URL(string: path)! as URL)
        
        let session = URLSession.shared
        
        let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
            let json:JSON = JSON(data as Any)
            onCompletion(json, error as NSError?)
        })
        task.resume()
    
    }
}

Solution

  • You have to mark both completion handlers with @escaping. Usually the compiler offers a fix

    class RestApiManager: NSObject {
        static let sharedInstance = RestApiManager()
    
        let baseURL = "http://api.randomuser.me/"
    
        func getRandomUser(onCompletion : @escaping (JSON) -> Void) {
            makeHTTPGetRequest(path: baseURL, onCompletion: { json, err -> Void in
                onCompletion(json)
            })
        }
    
        func makeHTTPGetRequest(path: String, onCompletion: @escaping ServiceResponse) {
            let request = NSMutableURLRequest(url : URL(string: path)! as URL)
    
            let session = URLSession.shared
    
            let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
                let json:JSON = JSON(data as Any)
                onCompletion(json, error as NSError?)
            })
            task.resume()
    
        }
    }