Created
March 26, 2015 22:30
-
-
Save dacur/655117412e845b4ff046 to your computer and use it in GitHub Desktop.
Sample code from an iOS project using Swift and open data.
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
// | |
// ViewController.swift | |
// RaleighCrime | |
// | |
// Created by David Curtis on 3/15/15. | |
// Copyright (c) 2015 David Curtis. All rights reserved. | |
// | |
import UIKit | |
import Foundation | |
import MapKit | |
import CoreLocation | |
class ViewController: UIViewController, MKMapViewDelegate { | |
@IBOutlet weak var mapView: MKMapView! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
resetMap() | |
} | |
func resetMap(){ | |
// Clear all annotations first | |
let annotationsToRemove = mapView.annotations | |
mapView.removeAnnotations(annotationsToRemove) | |
// Set starting point of map: downtown Raleigh | |
var latitude:CLLocationDegrees = 35.779632 | |
var longitude:CLLocationDegrees = -78.638094 | |
// Zoom level | |
var latDelta:CLLocationDegrees = 0.09 | |
var longDelta:CLLocationDegrees = 0.09 | |
var span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta) | |
var location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude) | |
var region:MKCoordinateRegion = MKCoordinateRegionMake(location, span) | |
mapView.setRegion(region, animated: true) | |
var annotation = MKPointAnnotation() | |
annotation.coordinate = location | |
annotation.title = "Raleigh" | |
annotation.subtitle = "North Carolina" | |
mapView.addAnnotation(annotation) | |
} | |
override func didReceiveMemoryWarning() { | |
super.didReceiveMemoryWarning() | |
// Dispose of any resources that can be recreated. | |
} | |
func retrieveJsonFromData(data: NSData) -> AnyObject?{ | |
var error : NSError? | |
let jsonObject : AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &error) | |
if error == nil { | |
println("Successfully deserialized") | |
if jsonObject is NSDictionary{ | |
let deserializedDictionary = jsonObject as NSDictionary | |
println("Deserialized JSON Dictionary = \(deserializedDictionary)") | |
} | |
else if jsonObject is NSArray{ | |
let deserialzedArray = jsonObject as NSArray | |
// println("Deserialzed JSON Array = \(deserialzedArray[0])") | |
return deserialzedArray | |
} | |
else{ | |
println("None") | |
} | |
} else if error != nil { | |
println("An error happened while deserializing JSON data") | |
} | |
return nil | |
} | |
@IBAction func buttonClick(sender: AnyObject) { | |
//click here to select crime button on home pg | |
} | |
@IBOutlet weak var selectCrimeButton: UIButton! | |
@IBAction func cancelToMainViewController(segue:UIStoryboardPopoverSegue) { | |
} | |
@IBAction func clearMap(segue:UIStoryboardSegue){ | |
resetMap() | |
selectCrimeButton.setTitle("Click Here to Select Crime", forState: nil) | |
} | |
@IBAction func murder(segue:UIStoryboardSegue){ | |
resetMap() | |
getCrime("lcr=11") | |
selectCrimeButton.setTitle("Murder", forState: nil) | |
} | |
@IBAction func sexOffenses(segue:UIStoryboardSegue){ | |
resetMap() | |
getCrime("lcr=17A") //forcible rape | |
getCrime("lcr=21") // rape by force | |
getCrime("lcr=22") // rape attempted | |
selectCrimeButton.setTitle("Rape", forState: nil) | |
} | |
@IBAction func allCrimes(segue:UIStoryboardSegue){ | |
resetMap() | |
getCrime("") | |
selectCrimeButton.setTitle("All Crimes", forState: nil) | |
} | |
@IBAction func robbery(segue:UIStoryboardSegue){ | |
resetMap() | |
getCrime("lcr=20A") | |
getCrime("lcr=20B") | |
selectCrimeButton.setTitle("Robbery", forState: nil) | |
} | |
@IBAction func burglary(segue:UIStoryboardSegue){ | |
resetMap() | |
getCrime("lcr=30A") | |
getCrime("lcr=30B") | |
selectCrimeButton.setTitle("Burglary", forState: nil) | |
} | |
@IBAction func assaultFirearm(segue:UIStoryboardSegue){ | |
resetMap() | |
getCrime("lcr=25A") // firearm | |
getCrime("lcr=41") // firearm | |
getCrime("lcr=A41") // assault LEO firearm | |
selectCrimeButton.setTitle("Assault with Firearm", forState: nil) | |
} | |
func getCrime(newQuery:String) { | |
var query = newQuery | |
var url = NSURL(string: "https://data.raleighnc.gov/resource/csw9-dd5k.json?\(query)") | |
let request = NSURLRequest(URL: url!) | |
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in | |
let parsedObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil) | |
var newData: AnyObject? = self.retrieveJsonFromData(data) | |
var latitudes : [NSString] = [] | |
var longitudes : [NSString] = [] | |
var dates : [NSString] = [] | |
var descriptions : [NSString] = [] | |
var dataDictionary = newData? as NSArray | |
var length = dataDictionary.count - 1 | |
let formatter = NSDateFormatter() | |
formatter.dateStyle = NSDateFormatterStyle.LongStyle | |
formatter.timeStyle = NSDateFormatterStyle.MediumStyle | |
for index in 0...length { | |
if var location = dataDictionary[index]["location"] as? NSDictionary{ | |
latitudes.append(location["latitude"] as NSString) | |
longitudes.append(location["longitude"] as NSString) | |
} | |
if var date = dataDictionary[index]["inc_datetime"] as? NSString { | |
// println(date) | |
dates.append(date) | |
} | |
if var description = dataDictionary[index]["lcr_desc"] as? NSString { | |
descriptions.append(description) | |
} | |
} | |
var newDateFormat : [NSString] = [] | |
var newTimeFormat : [NSString] = [] | |
var datesLength = dates.count - 1 | |
for index in 0...datesLength { | |
var formattedDate = self.reformatDate(dates[index]) | |
var formattedTime = self.reformatTime(dates[index]) | |
newDateFormat.append(formattedDate) | |
newTimeFormat.append(formattedTime) | |
} | |
var latDelta:CLLocationDegrees = 0.09 | |
var longDelta:CLLocationDegrees = 0.09 | |
var span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta) | |
var arrayLength = latitudes.count - 1 | |
for index in 0...arrayLength { | |
var newLat:CLLocationDegrees = latitudes[index].doubleValue | |
var newLong:CLLocationDegrees = longitudes[index].doubleValue | |
var newLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(newLat, newLong) | |
var annotation = MKPointAnnotation() | |
annotation.coordinate = newLocation | |
annotation.title = "\(newDateFormat[index]) at \(newTimeFormat[index])" | |
// annotation.subtitle = newTimeFormat[index] | |
annotation.subtitle = descriptions[index] | |
self.mapView.addAnnotation(annotation) | |
} | |
} | |
} | |
func reformatDate(date: NSString) -> NSString { | |
var newDate = date.substringToIndex(10) | |
return newDate | |
} | |
func reformatTime(time: NSString) -> NSString { | |
let range1:NSRange = NSMakeRange(11, 5) | |
var newTime = time.substringWithRange(range1) | |
return newTime | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment