Advertisement
Guest User

Untitled

a guest
Aug 24th, 2016
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.03 KB | None | 0 0
  1. //We have some class, HTTPManager, that allows us to perform a GET request to a URL.
  2. //Upon successful fetch of the data, the success closure is executed with the data (represented as NSData,
  3. //more or less the raw bytes) and the calling function can then do what it needs with the data.
  4. //the method signature of HTTPManager.get() is   class func get(url: String, success: (data: NSData) -> Void, failure: (error: //String) -> Void) { }
  5.        
  6. HTTPManager.get("www.example.com", success: { (data) in
  7.    
  8.     //we wrap this in a do/catch block (essentially a try/except block) because .JSONObjectWithData() can throw an Error.
  9.  
  10.     do {
  11.        
  12.         //we declare it [String: AnyObject] because the types of the values in the JSON object cannot be automatically inferred.
  13.  
  14.         let json: [String: AnyObject]? = try NSJSONSerialization.JSONObjectWithData(data: data, options: NSJSONReadingOptions.MutableContainers) as? [String: AnyObject]
  15.  
  16.     <if the json is not nil, do whatever you need with it>
  17.  
  18.     } catch {
  19.  
  20.  
  21.     }
  22.  
  23.     }, failure: { (error) in
  24.  
  25.  
  26.  
  27. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement