Skip to content

Instantly share code, notes, and snippets.

@abelesmw
Last active February 18, 2016 21:46
Show Gist options
  • Save abelesmw/f7de36151871eff5b3af to your computer and use it in GitHub Desktop.
Save abelesmw/f7de36151871eff5b3af to your computer and use it in GitHub Desktop.
Grab neighborhood by user location
//
// ViewController.swift
// Find Your Hood
//
// Created by Mark Abeles
// Copyright (c) 2016 Mabeles. All rights reserved.
//
import UIKit
import CoreLocation
import SystemConfiguration
import SystemConfiguration
public class Reachability {
// Check if internet connection is available
class func isConnectedToNetwork() -> Bool {
var status:Bool = false
let url = NSURL(string: "https://google.com")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "HEAD"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
request.timeoutInterval = 10.0
var response:NSURLResponse?
do {
let _ = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response) as NSData?
}
catch let error as NSError {
print(error.localizedDescription)
}
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode == 200 {
status = true
}
}
return status
}
}
extension UIView {
func rotate360Degrees(duration: CFTimeInterval = 10.0, completionDelegate: AnyObject? = nil) {
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0.0
rotateAnimation.toValue = CGFloat(M_PI * 30.0)
rotateAnimation.duration = duration
if let delegate: AnyObject = completionDelegate {
rotateAnimation.delegate = delegate
}
self.layer.addAnimation(rotateAnimation, forKey: nil)
}
}
class ViewController: UIViewController, CLLocationManagerDelegate {
var manager:CLLocationManager!
@IBOutlet weak var dotLine: UIImageView!
var internet:Bool = false
//global variables for latitude and longitude, reference with self.lat & self.lon in other functions
var lat:Double?
var lon:Double?
let viewColor = UIColor(red: 237/255, green: 234/255, blue: 239/255, alpha: 1.0)
let status = Reach().connectionStatus()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = viewColor
manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy - kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
self.removeAnimation()
print(lat)
print(lon)
}
@IBAction func button2(sender: AnyObject) {
self.showAnimation()
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) { [unowned self] in
if Reachability.isConnectedToNetwork() {
dispatch_async(dispatch_get_main_queue()) {
// handle if you are connected to network here
if (self.lat == nil || self.lon == nil) {
self.createAlert()
self.dotLine.hidden = true
//self.dotLine.removeFromSuperview()
} else {
let fullUrl = NSURL(string:"http://www.gnarledrootdesigns.com/nychoods/api?lat=\(self.lat!)&lon=\(self.lon!)")
//let fullUrl = NSURL(string:"google.com")
let task = NSURLSession.sharedSession().dataTaskWithURL(fullUrl!, completionHandler: {(data, response, error) in
let urlResponse:NSHTTPURLResponse = response as! NSHTTPURLResponse
if (urlResponse.statusCode == 200) {
self.showNeighborhood(data)
} else {
self.createAlert()
}
print(NSString(data: data!, encoding: NSUTF8StringEncoding))
})
task.resume()
print(fullUrl)
}
}
} else {
dispatch_async(dispatch_get_main_queue()) {
// handle when you aren't connected to network
self.createAlertInt2()
print("no internet")
//self.dotLine.hidden = true
//self.dotLine.removeFromSuperview()
}
}
}
}
func showNeighborhood(data: NSData?) {
let neighborhood = NSString(data:data!, encoding:NSUTF8StringEncoding)
let next = self.storyboard?.instantiateViewControllerWithIdentifier("NeighborhoodVC") as! NeighborhoodViewController
next.neighborhood = neighborhood
//self.presentViewController(next, animated: false, completion: nil)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.presentViewController(next, animated: false) { () -> Void in
}
})
}
func createAlert(){
let alert = UIAlertController(title: "Hey Homie", message: "Looks like something messed up broh, try again?", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in
//self.dismissViewControllerAnimated(true, completion: nil)
self.removeAnimation()
}))
self.presentViewController(alert, animated: false, completion: nil)
}
func createAlertInt(){
let alert = UIAlertController(title: "Hey Homie", message: "You may not have internet - try again when you find some", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Cool", style: .Default, handler: { (action) -> Void in
self.removeAnimation()
}))
self.presentViewController(alert, animated: false, completion: nil)
}
func createAlertInt2(){
let alertController = UIAlertController(title: "Hey Homie", message: "You may not have internet - try again when you find some", preferredStyle: .Alert)
let okAction = UIAlertAction(title: "Cool", style: UIAlertActionStyle.Default) {
UIAlertAction in
self.removeAnimation()
}
alertController.addAction(okAction)
self.presentViewController(alertController, animated: false, completion: nil)
}
func removeAnimation(){
print("animation canceled")
self.dotLine.hidden = true
}
func showAnimation() {
self.dotLine.hidden = false
self.dotLine.rotate360Degrees()
}
//function to adjust latitude and longitude labels
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation:CLLocation = locations[0]
// self.latitudeLabel.text = "\(userLocation.coordinate.latitude)"
//self.longitudeLabel.text = "\(userLocation.coordinate.longitude)"
self.lat = userLocation.coordinate.latitude
self.lon = userLocation.coordinate.longitude
}
func locationUnavailableError() {
print("this is an error")
}
override func shouldAutorotate() -> Bool {
if (UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeLeft ||
UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeRight ||
UIDevice.currentDevice().orientation == UIDeviceOrientation.Unknown) {
return false
}
else {
return true
}
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return [UIInterfaceOrientationMask.Portrait ,UIInterfaceOrientationMask.PortraitUpsideDown]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment