Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improving sorting of API values #2

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
290 changes: 201 additions & 89 deletions Team-Tiger/Team-Tiger/ButtonsViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,31 +11,64 @@ import Alamofire
import SwiftyJSON
import MapKit
import CoreData
//import CircleMenu
import Foundation

class ButtonsViewController: UIViewController, CLLocationManagerDelegate {

var FMdictionary = [:]
var dictionaryWithInfo = [String:String]()
var farmersMarketArray: [[String:String]] = []
var FMdictionary = []
var dictionaryWithInfo = [String:AnyObject]()
var farmersMarketArray: [[String:AnyObject]] = []
var arrayOfFarmersMarkets: [String] = []
var arrayOfParks: [String] = []
let locationManager = CLLocationManager()

let dataStore = DataStore()

var queue = NSOperationQueue()

override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
print("Yay for location")
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locationManager.requestLocation()

queue.addOperationWithBlock {

NSOperationQueue.mainQueue().addOperationWithBlock {
self.getLocation()
print("Location located")
}

NSOperationQueue.mainQueue().addOperationWithBlock {
self.getFarmersMarkets()

print("Farmers markets")

}
NSOperationQueue.mainQueue().addOperationWithBlock {
// self.getParks()

print("All the parks")

}
NSOperationQueue.mainQueue().addOperationWithBlock {
// self.getOutdoorWifiSpots()

print("Wifi Found")

}
NSOperationQueue.mainQueue().addOperationWithBlock {

// print("Count: \(self.outdoorWifiSpots.count)")
}

} else {
print("No go on location")
}
// queue.addOperationWithBlock {
//
//
// }
// queue.addOperationWithBlock {
//
//
// // }



Expand All @@ -45,152 +78,231 @@ class ButtonsViewController: UIViewController, CLLocationManagerDelegate {

}


override func viewWillAppear(animated: Bool) {

let apiClient = ParksApiClient()
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


func isLessThan5MilesAway(array : [String: AnyObject]) ->Bool {
return (array["Distance"] as? Double) < 5
}

// Parks

func getParks() {
print("Get parks")
let apiClient = ParksApiClient()

apiClient.populateParkByTypeBasedOnState("type", type: "Garden") {
print(apiClient.typeResults)
print(apiClient.typeResults)
let sortByDistance = NSSortDescriptor(key: "Distance", ascending: true)
var tableViewArray : NSArray = apiClient.typeResults
tableViewArray = tableViewArray.sortedArrayUsingDescriptors([sortByDistance])
apiClient.typeResults = tableViewArray as! [[String: AnyObject]]

// self.arrayOfParks = apiClient.typeResults

print("Maybe sorted \(apiClient.typeResults)")

for park in apiClient.typeResults {

// if self.isLessThan5MilesAway(park) {
self.arrayOfParks.append(park["name"] as! String)


}

print("Names \(self.arrayOfParks)")



}


fmParse { completion in
}

// Farmers' Marker
// Tweaked to get hours and season of operation

func getFarmersMarkets() {
self.fmParse { completion in

if completion {
for marketDictionary in self.farmersMarketArray {
// if self.isLessThan5MilesAway(marketDictionary) {
if let marketName = marketDictionary["name"] {
self.arrayOfFarmersMarkets.append(marketName)

self.arrayOfFarmersMarkets.append(marketName as! String)

}
}
NSOperationQueue.mainQueue().addOperationWithBlock({
// self.tableView.reloadData()
})
} else {
print("ERROR: Unable to retrieve farmer's markets")
}
// self.getCoordinates()
print(self.arrayOfFarmersMarkets)


}
}
func sortMarkets(array : [[String : AnyObject]]) -> [[String : AnyObject]] {
var arrayCopy : [[String : AnyObject]] = []

let sortByDistance = NSSortDescriptor(key: "Distance", ascending: true)
var tableViewArray : NSArray = array

tableViewArray = tableViewArray.sortedArrayUsingDescriptors([sortByDistance])
arrayCopy = tableViewArray as! [[String: AnyObject]]

return arrayCopy
}

func fmParse(completionHandler: (Bool) -> ()) {


Alamofire.request(.GET, "https://data.cityofnewyork.us/api/views/j8gx-kc43/rows.json?") .responseJSON { response in
self.FMdictionary = response.result.value as! NSDictionary

Alamofire.request(.GET, "https://data.ny.gov/resource/farmersmarkets.json?") .responseJSON { response in
self.FMdictionary = response.result.value as! NSArray
print("parsing")
if let jsonData = response.data {
let jsonObj = JSON(data: jsonData)

let arrayOfData = jsonObj["data"].array
let arrayOfData = jsonObj.array

if let arrayOfData = arrayOfData {

// print(arrayOfData)
for detail in arrayOfData {

self.dictionaryWithInfo["name"] = detail[8].string
self.dictionaryWithInfo["zip"] = detail[13].string
self.dictionaryWithInfo["longitude"] = detail[15].string
self.dictionaryWithInfo["latitude"] = detail[14].string

if let addressInDictionary = detail[10].string {
self.dictionaryWithInfo.removeAll()
if detail["county"] == "Kings" || detail["county"] == "Queens" || detail["county"] == "New York" || detail["county"] == "Bronx" || detail["county"] == "Richmond" {
self.dictionaryWithInfo["name"] = detail["market_name"].string
self.dictionaryWithInfo["zip"] = detail["zip"].string
self.dictionaryWithInfo["hours"] = detail["operation_hours"].string
self.dictionaryWithInfo["season"] = detail["operation_season"].string

self.dictionaryWithInfo["address"] = addressInDictionary
if let latitude = detail["location_points"]["latitude"].string {
self.dictionaryWithInfo["latitude"] = Double(latitude)
}
if let longitude = detail["location_points"]["longitude"].string {
self.dictionaryWithInfo["longitude"] = Double(longitude)
}
if let addressInDictionary = detail["address_line_1"].string {
self.dictionaryWithInfo["address"] = addressInDictionary

} else {
print("IN SEARCH OF ADDRESS")
}

} else {
print("IN SEARCH OF ADDRESS")

//
if let location = self.locationManager.location {
let coordinates = CLLocation(latitude: (self.dictionaryWithInfo["latitude"] as! Double), longitude: (self.dictionaryWithInfo["longitude"] as! Double))
print(coordinates)
let distance = coordinates.distanceFromLocation(location)
// * 0.00062137

self.dictionaryWithInfo.updateValue(distance, forKey: "Distance")
// self.dictionaryWithInfo["Distance"] = distance as? Double
// print("Distance: \(self.dictionaryWithInfo["Distance"])")
}
self.farmersMarketArray.append(self.dictionaryWithInfo)
}

self.farmersMarketArray.append(self.dictionaryWithInfo)

}
completionHandler(true)
}
print("Count: \(self.farmersMarketArray.count)")
self.farmersMarketArray = self.sortMarkets(self.farmersMarketArray)
print(self.farmersMarketArray)
completionHandler(true)
}
}



// Do any additional setup after loading the view.
}
// Wifi
var linkNycWifiSpots : [[String : AnyObject]] = []
var outdoorWifiSpots : [[String : AnyObject]] = []

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
func getOutdoorWifiSpots() {

var locationArray = [[String : AnyObject]]()

Alamofire.request(.GET, "https://data.cityofnewyork.us/resource/jd4g-ks2z.json") .responseJSON {
response in
locationArray = response.result.value as! Array
print("parsing")
if let jsonData = response.data {
let jsonObj = JSON(data: jsonData)

let arrayOfData = jsonObj.array

if let arrayOfData = arrayOfData {

for location in arrayOfData {

if location["location_t"].string == ("Outdoor Kiosk") {
var tempDictionary : [String : AnyObject] = [:]
// print("Outdoor \(location["name"])")
if location["name"] != nil {
tempDictionary["name"] = location["name"].string
}
if location["location_t"] != nil {
tempDictionary["location_t"] = location["location_t"].string
}

if location["lon"] != nil {
tempDictionary["long"] = location["lon"].string
}

if location["ssid"] != nil {
tempDictionary["ssid"] = location["ssid"].string
}

if location["zip"] != nil{
tempDictionary["zip"] = location["zip"].string
}

if location["lat"] != nil {
tempDictionary["lat"] = location["lat"].string
}

print(tempDictionary)
self.outdoorWifiSpots.append(tempDictionary)
}
}
}
}
print(self.outdoorWifiSpots)
}
}


/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}

*/


@IBAction func shopTapped(sender: AnyObject) {




}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {



let destinationVC = segue.destinationViewController as! SearchResultsTableViewController

//print("Passing: \(self.arrayOfParks)")

if segue.identifier == "showParks" {

destinationVC.arrayOfNames = self.arrayOfParks

destinationVC.arrayOfNames = self.arrayOfParks
} else {

destinationVC.arrayOfNames = self.arrayOfFarmersMarkets

}

}

//Location Things
func getLocation() {
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
print("Yay for location")
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locationManager.requestLocation()
locationManager.startUpdatingLocation()
// completion()
} else {
print("No go on location")
}
}

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("We know where you are")
if locations.count > 0 {
dataStore.currentLocation = (locations.first)!
locationManager.stopUpdatingLocation()
print("You are here : \(dataStore.currentLocation)")
// print("You are here : \(dataStore.currentLocation)")
}
}


func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Failed to find user's location: \(error.localizedDescription)")
}
}

}