2016-10-21 58 views
0

我已经创建了一个函数,使用NSObject类中的完成处理程序来使用Web服务。然而,我没有得到一个方法来处理返回调用该函数。Swift 3:不适用于iOS中的完成处理程序

func getUser(url:String, completionHandler: @escaping (NSDictionary?, NSError?) ->()) { 

    let config = URLSessionConfiguration.default // Session Configuration 
    let session = URLSession(configuration: config) // Load configuration into Session 
    let url = URL(string: url)! 

    let task = session.dataTask(with: url, completionHandler: { 
     (data, response, error) in 

     if error != nil { 
      completionHandler(nil, error as NSError?) 
     } else { 
      do { 
       if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [NSDictionary: Any] { 
        completionHandler(json as NSDictionary?,nil) 
       } 
      } catch { 
       print("error in JSONSerialization") 
      } 
     } 
    }) 
    task.resume() 
} 
+0

如果您收到任何错误然后添加错误:如果JSON结果是nil

ADDING

您可以用这种方式处理它一样。 –

+0

我没有得到任何错误,但我该如何调用上面的方法返回的迅速 – Kashif

回答

1

你应该确保你的completionHandler被称为在每个情况:例如,当JSONSerialization抛出,你赶上和打印错误,但你不打电话给你completionHandler

do { 
    let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [NSDictionary: Any] 
    completionHandler(json,nil) 
} catch(let error) { 
    print(error) 
    completionHandler(nil, error) 
} 
+0

由于完成处理程序,但你可以让我知道调用上述功能的,请 – Kashif

+0

我加了一段代码@Kashif –

+0

谢谢,我有补充说 – Kashif

相关问题