This piece of code is working - It gives me a lot of JSON back, which I have yet to parse, but I'd like to show my code here first to get tips on how to improve what I already have:
VenueService.swift
class VenueService {
private let __kVenueServiceClientID = "CLIENT_ID"
private let __kVenueServiceClientSecret = "CLIENT_SECRET"
func performVenueLocationRequest(location: CLLocationCoordinate2D, identifier: NSString, completion: (venues: NSDictionary?, error: NSError?) -> ()) {
var error: NSError?
var response: NSURLResponse?
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(queue, {
if let data = NSURLConnection.sendSynchronousRequest(self.buildRequestForVenueLocation(location, identifier), returningResponse: &response, error: &error) {
if(error == nil) {
let responseDictionary: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: nil, error:&error)
if let responseDictionary = responseDictionary as? NSDictionary {
completion(venues: responseDictionary, error: nil)
}
} else {
completion(venues: nil, error: error)
}
} else {
println("There was a problem with the request...")
}
})
}
func todaysDate() -> NSString {
let date = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyMMdd"
return formatter.stringFromDate(date)
}
func buildRequestForVenueLocation(location: CLLocationCoordinate2D, _ identifier: NSString) -> NSURLRequest {
return NSURLRequest(URL: NSURL(string: "https://api.foursquare.com/v2/venues/search?ll=\(location.latitude),\(location.longitude)&radius=500&limit=50&categoryId=\(identifier)&client_id=\(__kVenueServiceClientID)&client_secret=\(__kVenueServiceClientSecret)&v=\(self.todaysDate())")!)
}
}
I use it like this in my ViewController
:
struct Location {
let location: CLLocationCoordinate2D
init() {
self.location = CLLocationCoordinate2D(latitude: 37.332331, longitude: -122.031219)
}
}
class ViewController: UIViewController {
let v = VenueService()
let l = Location()
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func testJSON(sender: AnyObject) {
v.performVenueLocationRequest(l.location, identifier: "4d4b7105d754a06374d81259", completion: { dict, err in
dispatch_async(dispatch_get_main_queue(), {
if let err = err {
println("if let \(err)")
} else {
if let dict = dict {
println("else: \(dict)")
}
}
})
})
}
}
One thing I'm really confused about:
Say I have an optional. I could use the if let
syntax to unwrap it, but is it the same to just say if optinalVariable == nil {} else optinalVariable!
?
In playground I get the same results.