Optional error while converting from Swift 2 to 3 in keyboardWillShow notification - ios

I am converting my app to Swift 3 at the moment and I have problems with this function I used to show the keyboard before.
Initializer for conditional binding must have Optional type, not 'CGFloat'
The error appears in the third line.
It's been a while since I've programmed the last time and so I am not sure how to solve this.
func keyboardWillShow(_ sender: Notification) {
if let userInfo = sender.userInfo {
if let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue.size.height {
let duration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as AnyObject).doubleValue
let edgeInsets = UIEdgeInsetsMake(0, 0, keyboardHeight, 0)
UIView.animate(withDuration: duration!, animations: { () -> Void in
self.tableView.contentInset = edgeInsets
self.tableView.scrollIndicatorInsets = edgeInsets
self.view.layoutIfNeeded()
})
}
}
}

This is one of those rare situations where I recommend force-unwrapping. You know the userInfo contains this information, and you are hosed if it doesn't. Moreover, there is no need to pass through AnyObject or to call cgRectValue; you can cast all the way down to a CGRect in a single move. So I would write:
let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as! CGRect).size.height
(Note that there is no if, because we are not doing a conditional binding; we simply cast, kaboom.)
[Note too that there is no need now to fetch the duration or to call animate or layoutIfNeeded; you can throw all of that away. We are already in an animation, and your changes to the contentInset and scrollIndicatorInsets will be animated in time to the keyboard.]

change
if let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue.size.height {
to
if let foo = userInfo[UIKeyboardFrameEndUserInfoKey] {
let keyboardHeight = (foo as as AnyObject).cgRectValue.size.height
--- UPDATE ---
or
if let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as AnyObject?).cgRectValue.size.height {
AnyObject? works because AnyObject can contain Optional itself. So you have to casting to Optional explicitly. Either AnyObject? or Optional<AnyObject> will work.

Related

Animate spinning image in Swift

I have a image that I would like to keep spinning if a button is pressed, until I call an action to stop the spinning. I tried these websites: https://www.andrewcbancroft.com/2014/10/15/rotate-animation-in-swift/ I had to made chances to the delegation, it crashes when I try to changed it
and https://bencoding.com/2015/07/27/spinning-uiimageview-using-swift/ just does not spin when I call the action. Thank you. Code is here below:
Andrewcbancroft.com:
extension UIView {
func rotate360Degrees(duration: CFTimeInterval = 1.0, completionDelegate: AnyObject? = nil) {
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0.0
rotateAnimation.toValue = CGFloat(M_PI * 2.0)
rotateAnimation.duration = duration
if let delegate: AnyObject = completionDelegate {
rotateAnimation.delegate = delegate //<- error "Cannot assign value of type 'AnyObject' to type 'CAAnimationDelegate?'"
}
self.layer.add(rotateAnimation, forKey: nil)
}
}
Trying to cast delegate as! CAAnimationDelegate will crash the application with error code Could not cast value of type 'test.ViewController' (0x1074a0a60) to 'CAAnimationDelegate' (0x10cede480) when trying to rotate the image.
Bending.com:
extension UIView {
func startRotating(duration: Double = 1) {
let kAnimationKey = "rotation"
if self.layer.animation(forKey: kAnimationKey) == nil {
let animate = CABasicAnimation(keyPath: "transform.rotation")
animate.duration = duration
animate.repeatCount = Float.infinity
animate.fromValue = 0.0
animate.toValue = Float(M_PI * 2.0)
self.layer.add(animate, forKey: kAnimationKey)
}
}
func stopRotating() {
let kAnimationKey = "rotation"
if self.layer.animation(forKey: kAnimationKey) != nil {
self.layer.removeAnimation(forKey: kAnimationKey)
}
}
}
When trying to call my image view to start rotating in my viewDidLoad method, nothing happens.
Errors explained:
You're passing the delegate in as AnyObject
func rotate360Degrees(duration: CFTimeInterval = 1.0, completionDelegate: AnyObject? = nil)
AnyObject doesn't conform to CAAnimationDelegate, so you can't use it as the delegate.
If you're certain you're passing in a controller that can be a proper delegate, then cast it to the right kind of delegate:
if let delegate = completionDelegate as? CAAnimationDelegate {
rotateAnimation.delegate = delegate
}
If you're doing this and it's crashing:
rotateAnimation.delegate = completionDelegate as! CAAnimationDelegate
Then you're not passing in a controller that conforms to CAAnimationDelegate
It might be simpler to not pass the delegate in at all and assign it outside of the extension.

stopping an asynchronous call once it's out in the wild in swift

I have some problems with my version of this loadingOverlay singleton.
What's supposed to happen, is it comes onto the screen, with a view and a label that has the text, "Loading, please wait." or something like that. then if loading is longer than 2 seconds (i've changed it to 10 for debugging) the text changes to a random cute phrase.
first of all the animation that should change the text doesn't seem to happen. instead, the text just instantly changes.
more importantly, If, for some reason, my asynchronous call block is executed multiple times, I only want the most recent call to it to run, and I want the previous instances of it to terminate before running.
I was reading about callbacks and promises, which look promising. Is that a swifty pattern to follow?
by the way, as I'm learning swift and iOS, I've been experimenting, and I tried [unowned self] and now i'm experimenting with [weak self], but I'm not really certain which is most appropriate here.
// from http://stackoverflow.com/questions/33064908/adding-removing-a-view-overlay-in-swift/33064946#33064946
import UIKit
class LoadingOverlay{
static let sharedInstance = LoadingOverlay()
//above swifty singleton syntax from http://krakendev.io/blog/the-right-way-to-write-a-singleton
var overlayView = UIView()
var spring: CASpringAnimation!
var springAway: CASpringAnimation!
var hidden = false
private init() {} //This line prevents others from using the default () initializer for this class
func setupSpringAnimation(startY: CGFloat, finishY: CGFloat) {
overlayView.layer.position.y = startY
spring = CASpringAnimation(keyPath: "position.y")
spring.damping = 10
spring.fromValue = startY
spring.toValue = finishY
spring.duration = 1.0
spring.fillMode = kCAFillModeBackwards
}
func showOverlay() {
print("show overlay")
overlayView.alpha = 1
hidden = false
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate,
let window = appDelegate.window {
setupSpringAnimation(-window.frame.height / 2, finishY: window.frame.height / 2)
let overlayViewFramesize = 0.65 * min(window.frame.height, window.frame.width)
overlayView.frame = CGRectMake(0, 0, overlayViewFramesize, overlayViewFramesize)
overlayView.center = window.center
overlayView.backgroundColor = UIColor.greenColor()
overlayView.clipsToBounds = true
overlayView.layer.cornerRadius = overlayViewFramesize / 8
let label = UILabel(frame: CGRectMake(0,0,overlayViewFramesize * 0.8 , overlayViewFramesize))
label.text = " \nLoading, please wait\n "
label.tag = 12
overlayView.addSubview(label)
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.numberOfLines = 0 //as many as needed
label.sizeToFit()
label.textAlignment = NSTextAlignment.Center
label.center = CGPointMake(overlayViewFramesize / 2, overlayViewFramesize / 2)
overlayView.bringSubviewToFront(label)
window.addSubview(overlayView)
overlayView.layer.addAnimation(spring, forKey: nil)
RunAfterDelay(10.0) {
if self.hidden == true { return }
//strongSelf boilerplate code technique from https://www.raywenderlich.com/133102/swift-style-guide-april-2016-update?utm_source=raywenderlich.com+Weekly&utm_campaign=ea47726fdd-raywenderlich_com_Weekly4_26_2016&utm_medium=email&utm_term=0_83b6edc87f-ea47726fdd-415681129
UIView.animateWithDuration(2, delay: 0, options: [UIViewAnimationOptions.CurveEaseInOut, UIViewAnimationOptions.BeginFromCurrentState, UIViewAnimationOptions.TransitionCrossDissolve], animations: { [weak self] in
guard let strongSelf = self else { return }
(strongSelf.overlayView.viewWithTag(12) as! UILabel).text = randomPhrase()
(strongSelf.overlayView.viewWithTag(12) as! UILabel).sizeToFit()
print ((strongSelf.overlayView.viewWithTag(12) as! UILabel).bounds.width)
(strongSelf.overlayView.viewWithTag(12) as! UILabel).center = CGPointMake(overlayViewFramesize / 2, overlayViewFramesize / 2)
}, completion: { (finished: Bool)in
print ("animation to change label occured")})
}
}
}
func hideOverlayView() {
hidden = true
UIView.animateWithDuration(1.0, delay: 0.0, options: [UIViewAnimationOptions.BeginFromCurrentState], animations: { [unowned self] in
//I know this is clunky... what's the right way?
(self.overlayView.viewWithTag(12) as! UILabel).text = ""
self.overlayView.alpha = 0
}) { [unowned self] _ in
//I know this is clunky. what's the right way?
for view in self.overlayView.subviews {
view.removeFromSuperview()
}
self.overlayView.removeFromSuperview()
print("overlayView after removing:", self.overlayView.description)
}
//here i have to deinitialize stuff to prepare for the next use
}
deinit {
print("Loading Overlay deinit")
}
}
What I basically wanted, was to be able to delay a block of code, and possibly cancel it before it executes. I found the answer here:
GCD and Delayed Invoking

Swift custom Keyboard Error

I keep getting an Cannot convert expression's type '[NSObject : AnyObject]?' to 'NSDictionary' error and I don't know what to do. I tried everything, looked everywhere. Can you please help? I am creating a custom keyboard in SWIFT and I am totally new at this so i could definitely use the help.
// Called when `UIKeyboardWillShowNotification` is sent.
func keyboardWillShow(aNotification: NSNotification) {
let info = aNotification.userInfo as NSDictionary **<<<<<<<<<ERROR HERE>>>>>>>**
let sizeBegin = info.objectForKey(UIKeyboardFrameBeginUserInfoKey).CGRectValue().size
let sizeEnd = info.objectForKey(UIKeyboardFrameEndUserInfoKey).CGRectValue().size
let duration = info.objectForKey(UIKeyboardAnimationDurationUserInfoKey).doubleValue
let curve = info.objectForKey(UIKeyboardAnimationCurveUserInfoKey).integerValue
var animationCurve: UIViewAnimationCurve
if let value = UIViewAnimationCurve.fromRaw(curve) {
animationCurve = value
} else {
animationCurve = UIViewAnimationCurve.EaseInOut
}
let insets = UIEdgeInsets(top: 44, left: 0, bottom: sizeEnd.height, right: 0)
UIView.animateWithDuration(duration, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
self.textView.contentInset = insets
self.textView.scrollIndicatorInsets = insets
}, completion: nil)
}
// Called when `UIKeyboardWillHideNotification` is sent.
func keyboardWillHide(aNotification: NSNotification) {
let info = aNotification.userInfo as NSDictionary **<<<<<<<<<<ERROR HERE>>>>>>**
let sizeBegin = info.objectForKey(UIKeyboardFrameBeginUserInfoKey).CGRectValue().size
let sizeEnd = info.objectForKey(UIKeyboardFrameEndUserInfoKey).CGRectValue().size
let duration = info.objectForKey(UIKeyboardAnimationDurationUserInfoKey).doubleValue
let curve = info.objectForKey(UIKeyboardAnimationCurveUserInfoKey).integerValue
var animationCurve: UIViewAnimationCurve
if let value = UIViewAnimationCurve.fromRaw(curve) {
animationCurve = value
} else {
animationCurve = UIViewAnimationCurve.EaseInOut
}
let insets = UIEdgeInsets(top: 44, left: 0, bottom: sizeEnd.height, right: 0)
UIView.animateWithDuration(duration, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
self.textView.contentInset = insets
self.textView.scrollIndicatorInsets = insets
}, completion: nil)
}
Your dictionary is of type [NSObject:AnyObject]? which is an Optional type that must be unwrapped to be used. Since it is an Optional, it could be nil. One safe way of dealing with this is to use the nil coalescing operator ?? to unwrap it:
let info = (aNotification.userInfo ?? [:]) as NSDictionary
That will either unwrap your dictionary if it is not nil or give you a new empty dictionary if it is nil.

Dictionary doesn't recognize key type (Updated)

I have
func keyboardWillShow(aNotification: NSNotification) {
//Collect information about keyboard using its notification.
let info = aNotification.userInfo
let duration = (info[UIKeyboardAnimationDurationUserInfoKey] as NSValue) as Double
let curve : AnyObject? = info[UIKeyboardAnimationCurveUserInfoKey]
let kbFrame : AnyObject? = (info[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue().size
}
How can I get these to be read without the
"[NSObject : AnyObject]? does not have a member named 'subscript' " error?
In beta versions of xCode this had worked, but as of xCode 6.1 it no longer works properly.
userInfo is optional Dictionary, so you can use optional binding to unwrap value. And CGSize is a struct, not a object, so change AnyObject to CGSize.
if let info = aNotification.userInfo {
let duration = (info[UIKeyboardAnimationDurationUserInfoKey] as NSValue) as Double
let curve : AnyObject? = info[UIKeyboardAnimationCurveUserInfoKey]
let kbFrame: CGSize = (info[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue().size
}

How to get a value from NSValue in Swift?

Here's what I've tried so far
func onKeyboardRaise(notification: NSNotification) {
var notificationData = notification.userInfo
var duration = notificationData[UIKeyboardAnimationDurationUserInfoKey] as NSNumber
var frame = notificationData[UIKeyboardFrameBeginUserInfoKey]! as NSValue
var frameValue :UnsafePointer<(CGRect)> = nil;
frame.getValue(frameValue)
}
But I always seem to crash at frame.getValue(frameValue).
It's a little bit confusing because the documentation for UIKeyboardFrameBeginUserInfoKey says it returns a CGRect object, but when I log frame in the console, it states something like NSRect {{x, y}, {w, h}}.
getValue() must be called with a pointer to an (initialized) variable
of the appropriate size:
var frameValue = CGRect(x: 0, y: 0, width: 0, height: 0)
frame.getValue(&frameValue)
But it is simpler to use the convenience method:
let frameValue = frame.CGRectValue() // Swift 1, 2
let frameValue = frame.cgRectValue() // Swift 3

Resources