How can I make this animation work? - swift

I was trying to animate a set of images using this tutorial: https://www.geekylemon.com/animated-loading-screen. I converted the code from objective c to swift in order to implement it into another project, but it seems like it doesn't work properly.
Well, on the the storyboard are three Image Views(AnitmationimageView beeing the same with "L1.png", Loadimageview and the background image of the view controller). I wanted to run the AnitmationimageView and after it a transition to L1,2,3,4 images and after them to Loadimageview and after it to the background image. But when I run the program it only shows me the transition from AnitmationimageView to Loadimageview and the transition from Loadimageview to the background image. Hope this helps in "diagnosing" my problem.
class ViewController: UIViewController {
#IBOutlet weak var AnitmationimageView: UIImageView!
#IBOutlet weak var Loadimageview: UIImageView!
var loading_1: UIImage!
var loading_2: UIImage!
var loading_3: UIImage!
override func viewDidLoad() {
super.viewDidLoad()
AnitmationimageView.animationImages = [UIImage(named: "L1.png"), UIImage(named: "L2.png"), UIImage(named: "L3.png"), UIImage(named: "L4.png")] as? [UIImage]
AnitmationimageView.animationRepeatCount = 1
AnitmationimageView.animationDuration = 3 as CFTimeInterval
AnitmationimageView.startAnimating()
perform(#selector(self.delay1), with: nil, afterDelay: 3)
delay1()
delay2()
delay3()
}
#objc func delay1() {
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(1.0)
AnitmationimageView.alpha = 0
UIView.commitAnimations()
perform(#selector(self.delay2), with: nil, afterDelay: 1.0)
}
#objc func delay2() {
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(1.0)
Loadimageview.alpha = 1
UIView.commitAnimations()
perform(#selector(self.delay3), with: nil, afterDelay: 1.5)
}
#objc func delay3() {
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(1.0)
Loadimageview.alpha = 0
UIView.commitAnimations()
}
}

Related

View Controller not transitioning to next view controller

I'm building a Quiz App and at the end of the quiz, upon clicking an answer, I want the screen to transition to the ResultViewController where the user's score is displayed. I linked a segue from my MCViewController to the new ResultViewController screen. But upon finishing the quiz, the screen just kinda goes dim, no errors.
MCViewController:
import UIKit
class MCViewController: UIViewController {
#IBOutlet weak var questionLabel: UILabel!
#IBOutlet weak var progressBar: UIProgressView!
#IBOutlet weak var aButton: UIButton!
#IBOutlet weak var bButton: UIButton!
#IBOutlet weak var cButton: UIButton!
#IBOutlet weak var dButton: UIButton!
let quiz =
[
Questions(q: "When did English settlement begin in Canada?", a: "1510", b: "1497", c: "1604", d: "1720", answer: "1604"),
Questions(q: "Who passed the Quebec Act of 1774?", a: "Canadian Parliament", b: "British Parliament", c: "Quebec Parliament", d: "The French majority", answer: "British Parliament"),
Questions(q: "Whose portrait is on the Canadian 10 dollar bill?", a: "Sir George Cartier", b: "Sir Etienne Tache", c: "Sir John A. Macdonald", d: "Sir Louis La Fontaine", answer: "Sir John A. Macdonald"),
Questions(q: "What are the responsibilities of the federal government?", a: "Matters of national and international concern.", b: "Matters of national concern.", c: "Matters of international concern.", d: "Matters of provincial concern.", answer: " Matters of national and international concern."),
Questions(q: "What is 'Habeas corpus'?", a: "The right to challenge unlawful detention by the state.", b: "The right to live and work anywhere in Canada.", c: "The right to speak freely.", d: " The right for peaceful assembly.", answer: "The right to challenge unlawful detention by the state.")
]
var questionNumber = 0
override func viewDidLoad() {
super.viewDidLoad()
updateUI()
}
#IBAction func answerPressed(_ sender: UIButton) {
let userAnswer = sender.currentTitle
let actualAnswer = quiz[questionNumber].answer
if (userAnswer == actualAnswer) {
sender.backgroundColor = UIColor.green
} else {
sender.backgroundColor = UIColor.red //END OF ARRAY, SHOULD TRANSITION TO RESULTVIEWCONTROLLER
}
if (questionNumber + 1 < quiz.count){
questionNumber += 1
} else {
let resultVC = ResultViewController()
self.present(resultVC, animated: true, completion: nil)
}
Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(updateUI), userInfo: nil, repeats: false)
}
#objc func updateUI() {
questionLabel.text = quiz[questionNumber].q
aButton.setTitle(quiz[questionNumber].a, for: .normal)
bButton.setTitle(quiz[questionNumber].b, for: .normal)
cButton.setTitle(quiz[questionNumber].c, for: .normal)
dButton.setTitle(quiz[questionNumber].d, for: .normal)
aButton.titleLabel?.adjustsFontSizeToFitWidth = true;
bButton.titleLabel?.adjustsFontSizeToFitWidth = true;
cButton.titleLabel?.adjustsFontSizeToFitWidth = true;
dButton.titleLabel?.adjustsFontSizeToFitWidth = true;
aButton.backgroundColor = UIColor.clear
bButton.backgroundColor = UIColor.clear
cButton.backgroundColor = UIColor.clear
dButton.backgroundColor = UIColor.clear
progressBar.progress = Float(questionNumber + 1) / Float(quiz.count)
}
}
ResultViewController:
import UIKit
class ResultViewController : UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
}
}
Here's a little bit of my picture if it helps:
This code...
let resultVC = ResultViewController()
self.present(resultVC, animated: true, completion: nil)
presents a ResultViewController that is created using the init initialiser, not from the storyboard. It is likely the case that you haven't written anything in ResultViewController.init, because you did everything in the storyboard, so it does nothing and shows a blank view.
Since you have a segue, you should perform that segue instead!
performSegue(withIdentifier: "MCResult", sender: nil)
You probably have some data that you want to pass to ResultViewController. Do that in prepare(for:):
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? ResultViewController {
// pass whatever you need to "vc"
}
}
You are in same storyBoard so, instantiate your viewController like
let resultVC = self.storyboard?.instantiateViewController(withIdentifier: "ResultViewControllerID") as! ResultViewController
self.present(resultVC, animated: true, completion: nil)
I am hoping, you are aware of the UIViewController storyboard ID

How do I give screenshot file a filename when sharing via UIActivityView

I have created a VC with a print and share friendly version of a bunch of calculations. When I press "share" there appears the little icon and all the share options which is great. I cannot figure out how to add a filename of some kind beside the little icon. I think this would look much more professional if I could get this accomplished.
Hope there is a simple solution someone could help with :)
Here is my code:
import UIKit
class EvenPrintableViewController: UIViewController {
#IBOutlet weak var widthSizeTransfer: UILabel!
#IBOutlet weak var heightSizeTransfer: UILabel!
#IBOutlet weak var lengthTransfer: UILabel!
#IBOutlet weak var calcOutput: UILabel!
// Instantiate variables for Even transfer
var largeSizeRelay: String?
var lengthSizeRelay: String?
var heightRelay: String?
var calcOutputRelay: String?
override func viewDidLoad() {
super.viewDidLoad()
// Sets share icon to share/print view
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareTapped))
// Assign labels to Metric Even VC values via instances above
widthSizeTransfer.text = witdhSizeRelay
heightSizeTransfer.text = heightSizeRelay
heightTransfer.text = heightRelay
calcOutput.text = calcOutputRelay
}
// Share function for share button
#objc func shareTapped() {
let renderer = UIGraphicsImageRenderer(size: view.bounds.size)
let image = renderer.image { ctx in
view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
}
let vc = UIActivityViewController(activityItems: [image], applicationActivities: [])
vc.excludedActivityTypes = [.assignToContact, .addToReadingList]
vc.popoverPresentationController?.barButtonItem = navigationItem.rightBarButtonItem
present(vc, animated: true)
}
}
First save the UIImage as a temporary png/jpg file:
guard let imageData = image.pngData() else { return }
Then save it as a temporary file, which lets you to choose a file name:
let tempDir = FileManager.default.temporaryDirectory
let imgFileName = "YOUR_IMG_FILE_NAME.png"
let tempImgDir = tempDir.appendingPathComponent(imgFileName)
try? imageData.write(to: tempImgDir)
Then you can share the URL instead:
// Your code
let vc = UIActivityViewController(activityItems: [tempImgDir], applicationActivities: [])
P.S. the file is only temporary.

errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled"

I am trying to display or upload UIImage and I am getting this error.
"errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled}"
import UIKit
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
// linked labels and UiButtons
#IBOutlet weak var ifix: UILabel!
#IBOutlet weak var UIImage: UIImageView!
let someImageView: UIImageView = {
let theImageView = UIImageView()
theImageView.translatesAutoresizingMaskIntoConstraints = false // call this property so the image is added to your view
return theImageView
}()
#IBAction func UploadImage(_ sender: UIButton) {
let myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerController.SourceType.photoLibrary
self.present(myPickerController, animated: true, completion: nil)
}
#objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any])
{
let image_data = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
let imageData:Data = image_data!.pngData()!
_ = imageData.base64EncodedString()
self.dismiss(animated: true, completion: nil)
}
#IBAction func UIShuffle(_ sender: UIButton) {
}
#IBAction func UIReset(_ sender: UIButton) {
}
override func viewDidLoad() {
super.viewDidLoad()
// additional setup after loading the view, typically from a nib.
view.addSubview(someImageView) //This add it the view controller without constraints
someImageViewConstraints() //This function is outside the viewDidLoad function that controls the constraints
}
// `.isActive = true` after every constraint
func someImageViewConstraints() {
someImageView.widthAnchor.constraint(equalToConstant: 180).isActive = true
someImageView.heightAnchor.constraint(equalToConstant: 180).isActive = true
someImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
someImageView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 28).isActive = true
}
}
This message is harmless. The message comes from the OS and is related to the OS keeping an eye out for any newly discovered extensions related to whatever your app is doing. I see it often on macOS when displaying an open file dialog. While browsing around for a file, the OS is checking to see if there are any file-related extensions it needs to load in order to show you something. When the user presses "OK" or "Cancel" it stops searching for the extensions and spits that message to the console. I gather iOS may be doing something similar, perhaps related to share or other user-file-related activities. The message does not indicate an error in your application.

flip card causes fatal error in swift

I am following this card flipping tutorial and instead of creating the UIView and the UIImageViews programmatically I have created these in my storyboard.
When I click the card, the animation kicks in and turns over to the front image, but when I click again, this creates a fatal error:
unexpectedly found nil while unwrapping an Optional value.
I can not figure out why this error occurs.
Here is the code which is the transformation of the above mentioned tutorial:
class FirstViewController: UIViewController {
#IBOutlet weak var flashCardView: UIView!
#IBOutlet weak var backImage: UIImageView!
#IBOutlet weak var frontImage: UIImageView!
var showingBack = true
override func viewDidLoad() {
super.viewDidLoad()
let singleTap = UITapGestureRecognizer(target: self, action: Selector("tapped"))
singleTap.numberOfTapsRequired = 1
flashCardView.addGestureRecognizer(singleTap)
flashCardView.addSubview(backImage)
view.addSubview(flashCardView)
}
func tapped() {
if (showingBack) {
UIView.transitionFromView(backImage, toView: frontImage, duration: 1, options: UIViewAnimationOptions.TransitionFlipFromRight, completion: nil)
showingBack = false
} else {
UIView.transitionFromView(frontImage, toView: backImage, duration: 1, options: UIViewAnimationOptions.TransitionFlipFromLeft, completion: nil)
//here I get the error when flipping the card back to the back image
showingBack = true
}
}
}
I believe that when you transition, the old image's reference count is decremented, and since they're declared as weak it is getting destroyed. Try removing the weak declarations, and it will probably work. Looking at the tutorial, they don't have weak.

Error Saving Text Views in NSUserDefault

I have 6 textViews and one button to save the text wrote in them.
The problem is that the button just save until the forth TextView, fifth and sixth are not saved properly , they just copy the text in third and fourth textviews
Example
First text view - Correctly saved
Second text view - Correctly saved
Third text view - Correctly saved
Fourth text view - Correctly saved
Fifth text view - Its a copy of the text on third text view
Sixth text view - Its a copy of the text on fourth text view
Save button.
It seems all code are ok and all of the text views are linked successfully , but the last two textViews still fail.
My code here:
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var labelUno: UILabel!
#IBOutlet weak var labelDos: UILabel!
#IBOutlet weak var primerTextView: UITextView!
#IBOutlet weak var segundoTextView: UITextView!
#IBOutlet weak var tercerTextView: UITextView!
#IBOutlet weak var cuartoTextView: UITextView!
#IBOutlet weak var quintoTextView: UITextView!
#IBOutlet weak var sextoTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
scrollView.contentSize.height = 2000
labelUno.text = "¿Qué significa el éxito para ti? , ¿significa ser millonario , ser famoso , contribuir de alguna manera a ayudar a muchas personas, ser un buen padre o madre de familia, ser el mejor en tu profesión??"
primerTextView.layer.borderWidth = 0.8
primerTextView.layer.borderColor = UIColor.blackColor().CGColor
primerTextView.layer.cornerRadius = 8.0
segundoTextView.layer.borderWidth = 0.8
segundoTextView.layer.borderColor = UIColor.blackColor().CGColor
segundoTextView.layer.cornerRadius = 8.0
tercerTextView.layer.borderWidth = 0.8
tercerTextView.layer.borderColor = UIColor.blackColor().CGColor
tercerTextView.layer.cornerRadius = 8.0
cuartoTextView.layer.borderWidth = 0.8
cuartoTextView.layer.borderColor = UIColor.blackColor().CGColor
cuartoTextView.layer.cornerRadius = 8.0
quintoTextView.layer.borderWidth = 0.8
quintoTextView.layer.borderColor = UIColor.blackColor().CGColor
quintoTextView.layer.cornerRadius = 8.0
sextoTextView.layer.borderWidth = 0.8
sextoTextView.layer.borderColor = UIColor.blackColor().CGColor
sextoTextView.layer.cornerRadius = 8.0
//Save Button
let stringKey = NSUserDefaults.standardUserDefaults()
segundoTextView.text = stringKey.stringForKey("key")
primerTextView.text = stringKey.stringForKey("key2")
tercerTextView.text = stringKey.stringForKey("key3")
cuartoTextView.text = stringKey.stringForKey("key4")
quintoTextView.text = stringKey.stringForKey("key5")
sextoTextView.text = stringKey.stringForKey("key6")
//Hide keyboard
//Hide keyboard with touching anywhere
var tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "DismissKeyboard")
view.addGestureRecognizer(tap)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
#IBAction func saveButton(sender: AnyObject) {
let myText = segundoTextView.text
let myText2 = primerTextView.text
let myText3 = tercerTextView.text
let myText4 = cuartoTextView.text
let myText5 = quintoTextView.text
let myText6 = sextoTextView.text
NSUserDefaults.standardUserDefaults().setObject(myText, forKey: "key2")
NSUserDefaults.standardUserDefaults().setObject(myText2, forKey: "key")
NSUserDefaults.standardUserDefaults().setObject(myText3, forKey: "key3")
NSUserDefaults.standardUserDefaults().setObject(myText4, forKey: "key4")
NSUserDefaults.standardUserDefaults().setObject(myText3, forKey: "key5")
NSUserDefaults.standardUserDefaults().setObject(myText4, forKey: "key6")
NSUserDefaults.standardUserDefaults().synchronize()
var alert = UIAlertController(title: "Guardado", message:"Tu texto se ha guardado", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
//Hide keyboard with return button
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
if text == "\n"
{
primerTextView.resignFirstResponder()
segundoTextView.resignFirstResponder()
tercerTextView.resignFirstResponder()
cuartoTextView.resignFirstResponder()
quintoTextView.resignFirstResponder()
sextoTextView.resignFirstResponder()
return false
}
return true
}
//Hide keyboard with touching anywhere
func DismissKeyboard(){
view.endEditing(true)
}
}
I guess that in this part:
NSUserDefaults.standardUserDefaults().setObject(myText, forKey: "key2")
NSUserDefaults.standardUserDefaults().setObject(myText2, forKey: "key")
NSUserDefaults.standardUserDefaults().setObject(myText3, forKey: "key3")
NSUserDefaults.standardUserDefaults().setObject(myText4, forKey: "key4")
NSUserDefaults.standardUserDefaults().setObject(myText3, forKey: "key5")
NSUserDefaults.standardUserDefaults().setObject(myText4, forKey: "key6")
It should be:
NSUserDefaults.standardUserDefaults().setObject(myText2, forKey: "key2")
NSUserDefaults.standardUserDefaults().setObject(myText, forKey: "key")
NSUserDefaults.standardUserDefaults().setObject(myText3, forKey: "key3")
NSUserDefaults.standardUserDefaults().setObject(myText4, forKey: "key4")
NSUserDefaults.standardUserDefaults().setObject(myText5, forKey: "key5")
NSUserDefaults.standardUserDefaults().setObject(myText6, forKey: "key6")
It looks like a copy/paste error: put myText5 and myText6 instead of myText3 and myText4 in the two last lines.