Creating Overlay / Polygon Mapkit Swift 5 - mapkit

I've tried to make an Overlay but nothing show on the map.
I want to make a 4 lines that make a shape like a square, that will show on the map (I added 4 CLLocationCoord).
What am I doing wrong?
Should I add some code?
I tried to add mapView.delegate = self but I don't know why it is doesn't work.
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController {
#IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
let regionInMeters: Double = 1000
override func viewDidLoad() {
super.viewDidLoad()
checkLocationServices()
//calling the method
addBoundry()
}
func addBoundry(){ //creation of a polygon
var points = [CLLocationCoordinate2DMake(52.284428, 20.989394),
CLLocationCoordinate2DMake(52.224534, 21.044326),
CLLocationCoordinate2DMake(52.209182, 20.948024),
CLLocationCoordinate2DMake(52.247143, 20.918842),]
let polygon = MKPolygon(coordinates: &points, count: points.count)
mapView.addOverlay(polygon)
}
func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
if overlay is MKPolygon {
let polygonView = MKPolygonRenderer(overlay: overlay)
polygonView.strokeColor = .magenta
return polygonView
}
return MKOverlayRenderer()
}
func setupLocationManager(){
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
}
func centerViewOnUserLocation () {
if let location = locationManager.location?.coordinate {
let region = MKCoordinateRegion.init(center: location, latitudinalMeters: regionInMeters, longitudinalMeters: regionInMeters)
mapView.setRegion(region, animated: true)
}
}
func checkLocationServices() {
if CLLocationManager.locationServicesEnabled() {
setupLocationManager()
checkLocationAuthorization()
} else {
// Show alert letting the user know they have to turn this on.
}
}
func checkLocationAuthorization() {
switch CLLocationManager.authorizationStatus() {
case .authorizedWhenInUse:
mapView.showsUserLocation = true
centerViewOnUserLocation()
locationManager.startUpdatingLocation()
break
case .denied:
// Show alert instructing them how to turn on perm
break
case .notDetermined:
locationManager.requestWhenInUseAuthorization()
break
case .restricted:
// Show an alert letting them know what's up
break
case .authorizedAlways:
break
}
}
}
extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else {return}
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let region = MKCoordinateRegion.init(center: center, latitudinalMeters: regionInMeters, longitudinalMeters: regionInMeters)
mapView.setRegion(region, animated: true)
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
checkLocationAuthorization()
}
}

mapView.delegate = self
works when your class implements MKMapViewDelegate.
something like
class ViewController: UIViewController, MKMapViewDelegate {

Related

Mkmap iOS11 clusters doesn't split up after max zoom, how to set it up?

First, my code is perfectly running.
I have well set up and mapView.register my annotation markers and cluster.
When I zoom out the annotations fusion as expected in my cluster views,
when I zoom in, same good result, except at a certain point. When too many annotations are too close from each other, the cluster view doesn't split up into my two annotation views anymore.
So I search a way to be able to setup this "zoom level" that will makes appear my two annotations even if there are really close from each other.
Here are my cluster views with a high zoom on the map:
Here if I zoom at the maximum:
Well, one of the cluster views split into two, but doesn't reveal the 4 annotations.
I also try to setup the displayPriority to be higher for my two annotations, than the cluster view, but the result is still the same.
Any ideas ?
You will need to keep track of the zoom level of the map, and reload your annotations when you cross a zoom level that you specify.
private let maxZoomLevel = 9
private var previousZoomLevel: Int?
private var currentZoomLevel: Int? {
willSet {
self.previousZoomLevel = self.currentZoomLevel
}
didSet {
// if we have crossed the max zoom level, request a refresh
// so that all annotations are redrawn with clustering enabled/disabled
guard let currentZoomLevel = self.currentZoomLevel else { return }
guard let previousZoomLevel = self.previousZoomLevel else { return }
var refreshRequired = false
if currentZoomLevel > self.maxZoomLevel && previousZoomLevel <= self.maxZoomLevel {
refreshRequired = true
}
if currentZoomLevel <= self.maxZoomLevel && previousZoomLevel > self.maxZoomLevel {
refreshRequired = true
}
if refreshRequired {
// remove the annotations and re-add them, eg
let annotations = self.mapView.annotations
self.mapView.removeAnnotations(annotations)
self.mapView.addAnnotations(annotations)
}
}
}
private var shouldCluster: Bool {
if let zoomLevel = self.currentZoomLevel, zoomLevel <= maxZoomLevel {
return false
}
return true
}
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
// https://stackoverflow.com/a/40616239/883413
let zoomWidth = mapView.visibleMapRect.size.width
let zoomLevel = Int(log2(zoomWidth))
self.currentZoomLevel = zoomLevel
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
// for me, annotation reuse doesn't work with clustering
let annotationView = CustomAnnotationView(annotation: annotation)
if self.shouldCluster {
annotationView.clusteringIdentifier = "custom-id"
} else {
annotationView.clusteringIdentifier = nil
}
return annotationView
}
In my case, ! EVERY TIME ! I didn't update the clusteringIdentifier
in "func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation)"
When the MKAnnotationView is reused by the mapView.dequeueReusableAnnotationView(withIdentifier: "identifier", for: annotation), the clusteringIdentifier will be nil. (reset)
That's the reason why the clusters doesn't work.
AnnotationView.swift
import MapKit
// MARK: - Define
struct AnnotationViewInfo {
static let identifier = "AnnotationView"
}
final class AnnotationView: MKAnnotationView {
// MARK: - Initializer
override init(annotation: MKAnnotation!, reuseIdentifier: String!) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
setView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setView()
}
// MARK: - Value
// MARK: Public
override var annotation: MKAnnotation? {
willSet { update(annotation: newValue) }
}
// MARK: - Function
// MARK: Private
private func setView() {
if #available(iOS 11.0, *) {
collisionMode = .rectangle
clusteringIdentifier = AnnotationViewInfo.identifier
}
canShowCallout = true
image = #imageLiteral(resourceName: "pin01").resizedImage(size: CGSize(width: #imageLiteral(resourceName: "pin01").size.width/4.0, height: #imageLiteral(resourceName: "pin01").size.height/4.0), scale: 1.0)
}
private func update(annotation: MKAnnotation?) {
if #available(iOS 11.0, *) {
clusteringIdentifier = AnnotationViewInfo.identifier
}
// TODO: Update the annotationView
}
}
MKMapViewDelegate
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if #available(iOS 11.0, *) {
switch annotation {
case is PointAnnotation: return mapView.dequeueReusableAnnotationView(withIdentifier: AnnotationView1Info.identifier, for: annotation)
case is MKClusterAnnotation: return mapView.dequeueReusableAnnotationView(withIdentifier: ClusterAnnotationViewInfo.identifier, for: annotation)
case is MKUserLocation: return nil
default: return nil
}
} else {
return nil
}
}
Key Point (You must update the "clusteringIdentifier" every time.)
private func update(annotation: MKAnnotation?) {
if #available(iOS 11.0, *) {
clusteringIdentifier = AnnotationViewInfo.identifier
}
// TODO: Update the annotationView
}
}
Sample Project Here

UIMenuItem #selector method crash in wkwebview

UIMenuItem selector method crashes in iOS 11 beta SDK.
-[WKContentView highlightText]: unrecognized selector sent to instance 0x7f85df8f3200
Method Definition:
func highlightText()
{
//
}
I try to add UIMenuItem in WKWebView,
let menuItemHighlight = UIMenuItem.init(title: "Highlight", action: #selector(ContentWebkitView.highlightText))
UIMenuController.shared.menuItems = [menuItemHighlight]
I was also getting this error when I was overriding canPerformAction and checking for my custom selector. In my case I wanted to remove all menu items except for my custom one and the following made this work for me.
class ViewController: UIViewController {
#IBOutlet weak var webView: MyWebView!
override func viewDidLoad() {
super.viewDidLoad()
loadWebView()
setupCustomMenu()
}
func loadWebView() {
let url = URL(string: "http://www.google.com")
let request = URLRequest(url: url!)
webView.load(request)
}
func setupCustomMenu() {
let customMenuItem = UIMenuItem(title: "Foo", action:
#selector(ViewController.customMenuTapped))
UIMenuController.shared.menuItems = [customMenuItem]
UIMenuController.shared.update()
}
#objc func customMenuTapped() {
let yay = "🤪🤪🤪🤪🤪🤪🤪🤪🤪🤪🤪🤪"
let alertView = UIAlertController(title: "Yay!!", message: yay, preferredStyle: .alert)
alertView.addAction(UIAlertAction(title: "cool", style: .default, handler: nil))
present(alertView, animated: true, completion: nil)
}
}
class MyWebView: WKWebView {
// turn off all other menu items
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return false
}
}
OK, we finally made it work for Swift 4:
In your WKWebView subclass, add the following property and method:
// MARK: - Swizzling to avoid responder chain crash
var wkContentView: UIView? {
return self.subviewWithClassName("WKContentView")
}
private func swizzleResponderChainAction() {
wkContentView?.swizzlePerformAction()
}
Then, add an extension to UIView (I put it in the same file as my WKWebView subclass, you can make it fileprivate if you'd like)
// MARK: - Extension used for the swizzling part linked to wkContentView
extension UIView {
/// Find a subview corresponding to the className parameter, recursively.
func subviewWithClassName(_ className: String) -> UIView? {
if NSStringFromClass(type(of: self)) == className {
return self
} else {
for subview in subviews {
return subview.subviewWithClassName(className)
}
}
return nil
}
func swizzlePerformAction() {
swizzleMethod(#selector(canPerformAction), withSelector: #selector(swizzledCanPerformAction))
}
private func swizzleMethod(_ currentSelector: Selector, withSelector newSelector: Selector) {
if let currentMethod = self.instanceMethod(for: currentSelector),
let newMethod = self.instanceMethod(for:newSelector) {
let newImplementation = method_getImplementation(newMethod)
method_setImplementation(currentMethod, newImplementation)
} else {
print("Could not find originalSelector")
}
}
private func instanceMethod(for selector: Selector) -> Method? {
let classType = type(of: self)
return class_getInstanceMethod(classType, selector)
}
#objc private func swizzledCanPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return false
}
}
Now the UIMenuItem works as expected:
But honestly, this really feels like a hack, and I would love Apple to fix this issue :-/
Thanks for Stephan Heilner for his answer: https://stackoverflow.com/a/42985441/4670400

Update Location in Background every n minutes forever in Swift 2.0

With the code below in AppDelegate.swift I can get location updates every 30 seconds. However, after 180 seconds the background execution is kicked by backgroundTimeRemaining. The plist has the "location"tag in UIBackgroundModes
I have two questions:
Why the backgroundTimeRemaining is not resetting?
If I do startUpdatingLocation() and then stopUpdatingLocation() to save battery then I will not get location updated ever again.
import UIKit
import CoreLocation
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {
var window: UIWindow?
let locationManager = CLLocationManager()
var pos = 0
var LatitudeGPS = NSString()
var LongitudeGPS = NSString()
var speedGPS = NSString()
var Course = NSString()
var Altitude = NSString()
var bgtimer = NSTimer()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
var backgroundUpdateTask: UIBackgroundTaskIdentifier!
func beginBackgroundUpdateTask() {
self.backgroundUpdateTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({
self.endBackgroundUpdateTask()
})
}
func endBackgroundUpdateTask() {
UIApplication.sharedApplication().endBackgroundTask(self.backgroundUpdateTask)
self.backgroundUpdateTask = UIBackgroundTaskInvalid
}
func doBackgroundTask() {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
self.beginBackgroundUpdateTask()
// Do something
self.StartupdateLocation()
self.bgtimer = NSTimer.scheduledTimerWithTimeInterval(30, target: self, selector: "bgtimer:", userInfo: nil, repeats: true)
NSRunLoop.currentRunLoop().addTimer(self.bgtimer, forMode: NSDefaultRunLoopMode)
NSRunLoop.currentRunLoop().run()
// End the background task.
self.endBackgroundUpdateTask()
})
}
func bgtimer(timer:NSTimer!){
print("Fired from Background ************************************")
updateLocation()
print("Position Report: \(pos)")
}
func applicationDidEnterBackground(application: UIApplication) {
self.doBackgroundTask()
}
func StartupdateLocation() {
locationManager.delegate = self
locationManager.startUpdatingLocation()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.requestWhenInUseAuthorization()
locationManager.allowsBackgroundLocationUpdates = true
locationManager.pausesLocationUpdatesAutomatically = false
}
func updateLocation() {
pos++
//locationManager.startUpdatingLocation()
//locationManager.stopUpdatingLocation()
print("Latitude: \(LatitudeGPS)")
print("Longitude: \(LongitudeGPS)")
print("Speed: \(speedGPS)")
print("Heading: \(Course)")
print("Altitude BG: \(Altitude)")
print(UIApplication.sharedApplication().backgroundTimeRemaining)
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
LatitudeGPS = String(format: "%.10f", manager.location!.coordinate.latitude)
LongitudeGPS = String(format: "%.10f", manager.location!.coordinate.longitude)
speedGPS = String(format: "%.3f", manager.location!.speed)
Altitude = String(format: "%.3f", manager.location!.altitude)
Course = String(format: "%.3f", manager.location!.course)
}
}
EDIT ***
I solved the problem after I initialized the updateLocation in the ViewController.
import UIKit
import CoreLocation
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,CLLocationManagerDelegate {
var window: UIWindow?
var locationManager = CLLocationManager()
var backgroundUpdateTask: UIBackgroundTaskIdentifier!
var bgtimer = Timer()
var latitude: Double = 0.0
var longitude: Double = 0.0
var current_time = NSDate().timeIntervalSince1970
var timer = Timer()
var f = 0
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
self.doBackgroundTask()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
print("Entering foreBackground")
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
print("Entering Background")
// self.doBackgroundTask()
}
func doBackgroundTask() {
DispatchQueue.main.async {
self.beginBackgroundUpdateTask()
self.StartupdateLocation()
self.bgtimer = Timer.scheduledTimer(timeInterval:-1, target: self, selector: #selector(AppDelegate.bgtimer(_:)), userInfo: nil, repeats: true)
RunLoop.current.add(self.bgtimer, forMode: RunLoopMode.defaultRunLoopMode)
RunLoop.current.run()
self.endBackgroundUpdateTask()
}
}
func beginBackgroundUpdateTask() {
self.backgroundUpdateTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
self.endBackgroundUpdateTask()
})
}
func endBackgroundUpdateTask() {
UIApplication.shared.endBackgroundTask(self.backgroundUpdateTask)
self.backgroundUpdateTask = UIBackgroundTaskInvalid
}
func StartupdateLocation() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.requestAlwaysAuthorization()
locationManager.allowsBackgroundLocationUpdates = true
locationManager.pausesLocationUpdatesAutomatically = false
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error while requesting new coordinates")
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
self.latitude = locValue.latitude
self.longitude = locValue.longitude
f+=1
print("New Coordinates: \(f) ")
print(self.latitude)
print(self.longitude)
}
#objc func bgtimer(_ timer:Timer!){
sleep(2)
/* if UIApplication.shared.applicationState == .active {
timer.invalidate()
}*/
self.updateLocation()
}
func updateLocation() {
self.locationManager.startUpdatingLocation()
self.locationManager.stopUpdatingLocation()
}}
I added the sleep function to delay of calling the location and send the information to server
Since this is running in both the app is active and goes to background. If you want only background process, remove or comment the function self.doBackgroundTask() from didFinishLaunchingWithOptions and remove the comment for self.doBackgroundTask() in the applicationdidEnterBackground. And then remove the comment in the function bgtimer(), since the background process has to stop once the app comes to active state.
Thank you using your code only i can able to made some
alternative solution to running continuously.

UIKeyboardDidShowNotification is called twice

In my UIViewController there are two UITextField at the bottom. So on keyboard appear I'm trying to move then above. Below is my code for handling keyboard
override func viewWillAppear(animated: Bool) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardShown:", name: UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardHidden:", name: UIKeyboardDidHideNotification, object: nil)
}
override func viewWillDisappear(animated: Bool) {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardDidHideNotification, object: nil)
}
// MARK: - Handling Notification
func keyboardShown(notification: NSNotification){
if let initialFrame = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() {
let convertedFrame = self.view.convertRect(initialFrame, fromView: nil)
iY = viewLogin.frame.origin.y
var currentFrame = viewLogin.frame
currentFrame.origin.y = convertedFrame.origin.y - 140
self.viewLogin.frame = currentFrame
UIView.animateWithDuration(0.2, animations: { () -> Void in
})
}
}
func keyboardHidden(notification: NSNotification){
var currentFrame = viewLogin.frame
currentFrame.origin.y = iY
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.viewLogin.frame = currentFrame
})
}
It's working fine for first UITextField. But, when I try to move to second UITextField then again keyboardShown() is called and my view move back to bottom. I'm not able to detect the actual cause. Please let me know if I'm missing anything.
Thanks in advance
Issue was related to the AutoLayout. I solved it as below
// MARK: - Handling Notification
func keyboardShown(notification: NSNotification){
self.bottomConstraint.constant += 125
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.viewLogin.layoutIfNeeded()
})
}
func keyboardHidden(notification: NSNotification){
self.bottomConstraint.constant -= 125
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.viewLogin.layoutIfNeeded()
})
}
We need to change the property of constraint, if we had used AutoLayout.

Presenting UIViewController touch events not registering

I have a custom transition event going on with my view controllers where view controller a (VC_A) will present (VC_B).
Now when doing the transition, VC_A will still exist, but VC_B will not receive any touch events. Now if I remove the view from VC_A, VC_B will get touch events. I am not sure what I am missing in my transition that tells the app to be sending all touch events to VC_B not VC_A. I have tried setting the first responder, but that did not work, if somebody could tell me what I am missing, it would be appreciated.
//
// AnimationController.swift
// MarineWars
//
// Created by Anthony Randazzo on 5/6/15.
// Copyright (c) 2015 Anthony Randazzo. All rights reserved.
//
import Foundation
import UIKit
class TransitioningDelegate: NSObject, UIViewControllerTransitioningDelegate {
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return AnimationController(transitionType: .Presenting)
}
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return AnimationController(transitionType: .Dismissing)
}
func interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning?
{
return nil;
}
}
private var inSuperView : UIView?;
private var toSuperView : UIView?;
class AnimationController: NSObject, UIViewControllerAnimatedTransitioning {
enum TransitionType {
case Presenting
case Dismissing
}
var animationTransitionOptions: UIViewAnimationOptions
var inView : UIView?;
var toView : UIView?;
var fromView : UIView?;
init(transitionType: TransitionType) {
switch transitionType {
case .Presenting:
animationTransitionOptions = .TransitionFlipFromLeft
case .Dismissing:
animationTransitionOptions = .TransitionFlipFromRight
}
super.init()
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
inView = transitionContext.containerView()
toView = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)?.view // if iOS 8 only, I'd use `viewForKey`, instead
fromView = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)?.view
if(animationTransitionOptions == .TransitionFlipFromLeft)
{
NSTimer.scheduledTimerWithTimeInterval(transitionDuration(transitionContext)/2, target: self, selector: Selector("fireHalfwayIn"), userInfo: nil, repeats: false);
}
else if(animationTransitionOptions == .TransitionFlipFromRight)
{
NSTimer.scheduledTimerWithTimeInterval(transitionDuration(transitionContext)/2, target: self, selector: Selector("fireHalfwayOut"), userInfo: nil, repeats: false);
}
var scene = GameScene.instance;
scene!.paused = false;
scene!.view?.paused = false;
UIView.transitionFromView(fromView!, toView: toView!, duration: transitionDuration(transitionContext), options: animationTransitionOptions | .CurveEaseInOut | .AllowAnimatedContent) { finished in
transitionContext.completeTransition(true)
NSNotificationCenter.defaultCenter().postNotificationName("DropNotifications",object:nil);
//inSuperView is our parent
if(inSuperView == nil)
{
inSuperView = self.fromView;
println(self.fromView);
for view in self.fromView!.subviews
{
for subview in view.subviews
{
if(subview.isMemberOfClass(GameSceneView))
{
self.fromView!.resignFirstResponder()
self.toView!.becomeFirstResponder();
(subview as! GameSceneView).removeScene();
return;
}
}
if(view.isMemberOfClass(GameSceneView))
{
self.fromView!.resignFirstResponder()
self.toView!.becomeFirstResponder();
(view as! GameSceneView).removeScene();
return;
}
}
}
else
{
for view in self.toView!.subviews
{
for subview in view.subviews
{
if(subview.isMemberOfClass(GameSceneView))
{
(subview as! GameSceneView).createScene();
break;
}
}
}
}
}
}
func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
return 1.0
}
func fireHalfwayIn()
{
//println("\nFire In\n");
var scene = GameScene.instance;
//scene!.paused = false;
if(scene!.player.grid.parent != nil)
{
scene!.currentPlayer = scene!.enemy;
scene!.player.grid.removeFromParent();
scene!.addChild(scene!.enemy.grid);
var player = scene!.currentPlayer;
player!.grid.position = GameScene.fixPositionOnScreen(CGPointMake(toView!.frame.width/2 - player!.gridSize.width/2, toView!.frame.height/2 - player!.gridSize.height/2),currentPlayer: player!);
}
}
func fireHalfwayOut()
{
// println("\nFire Out\n");
var scene = GameScene.instance;
if(scene!.enemy.grid.parent != nil)
{
scene!.enemy.grid.removeFromParent();
scene!.currentPlayer = scene!.player;
scene!.addChild(scene!.player.grid);
}
}
}
OK I found the problem, I need to add the view to the content subview
if(self.presenting)
{
self.inView!.addSubview(self.toView!);
}
This of course leads to a bug when a context is completed, removing the from view from the key window.
So I needed to add this line after the context completed:
UIApplication.sharedApplication().keyWindow!.addSubview(self.toView!);
to get it to properly work