how to pass variable value to outside of URLSession async - swift 3

前端 未结 3 829

I have this code :

let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
    if error != nil {
              


        
3条回答
  •  醉酒成梦
    2020-12-07 07:14

    I would suggest to use a completion handler.

    func foo(withCompletion completion: (String?, Error?) -> Void) {
        let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
            if error != nil {
                completion(nil, error)
                return    
            }    
    
            do {        
                let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
    
                if let parseJSON = json {        
                    let details = parseJSON["detail"] as? String
    
                    completion(details, nil)        
                } // parse json end    
            } // do end                
            catch {         
                completion(nil, error)  
            }   
        } // let task end
    }
    

提交回复
热议问题