Created
July 16, 2014 15:07
-
-
Save seyhunak/aa98b2c229a321f2a258 to your computer and use it in GitHub Desktop.
HTTP Requests - Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func JSONParseDict(jsonString:String) -> Dictionary<String, AnyObject> { | |
var e: NSError? | |
var data: NSData = jsonString.dataUsingEncoding( | |
NSUTF8StringEncoding) | |
var jsonObj = NSJSONSerialization.JSONObjectWithData( | |
data, | |
options: NSJSONReadingOptions(0), | |
error: &e) as Dictionary<String, AnyObject> | |
if e { | |
return Dictionary<String, AnyObject>() | |
} else { | |
return jsonObj | |
} | |
} | |
func HTTPGetJSON( | |
url: String, | |
callback: (Dictionary<String, AnyObject>, String?) -> Void) { | |
var request = NSMutableURLRequest(URL: NSURL(string: url)) | |
request.setValue(“application/json”, forHTTPHeaderField: “Accept”) | |
HTTPsendRequest(request) { | |
(data: String, error: String?) -> Void in | |
if error { | |
callback(Dictionary<String, AnyObject>(), error) | |
} else { | |
var jsonObj = JSONParseDict(data) | |
callback(jsonObj, nil) | |
} | |
} | |
} | |
HTTPGetJSON(“http://gdata.youtube.com/feeds/api/standardfeeds/most_popular?v=2&alt=json") { | |
(data: Dictionary<String, AnyObject>, error: String?) -> Void in | |
if error { | |
println(error) | |
} else { | |
if let feed = data[“feed”] as? NSDictionary { | |
if let entries = feed[“entry”] as? NSArray { | |
for elem: AnyObject in entries { | |
let dict = elem as NSDictionary | |
if let titledict = dict[“title”] as? NSDictionary { | |
if let title = titledict[“$t”] as? NSString { | |
println(title) | |
} | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment