I am currently making an App for my grandson who has been diagnosed with Autism. One of the games I am putting on the app is a simple flash card game. Hit the button it produces a random image with a letter. I want add sound to the random image. example if image A appears the sound for letter A happens. I know how to add the sound to a file, just not sure how to figure out how to get the sound to match the random image. Here is my code. Any help greatly appreciated.
import UIKit
import AVFoundation
class Say_It_VC: UIViewController {
#IBOutlet var imageOne: UIImageView!
let imageNames = ["A3","B3","C3","D3","E3","F3","G3","H3","I3","J3","K3","L3","M3","N3","O3","P3","Q3","R3","S3","T3","U3","V3","W3","X3","Y3","Z3"]
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func showImages(_ sender: Any) {
let leftNumber:Int = Int (arc4random_uniform(26))
imageOne.image = UIImage (named: imageNames[leftNumber])
}
}
Related
I'm just learning Swift, and whenever I test my app, only a white blank screen is displayed on the simulator, however, when I close Xcode, the app loads up on the simulator and it works fine, does anyone know what's the reason for this?
Thank you very much in advance!
screenshot before closing xcode:
click to see
screenshot after closing xcode:
click to see
the code I used:
import UIKit
import SwiftUI
class ViewController: UIViewController {
#IBOutlet weak var priceTxt:UITextField!
#IBOutlet weak var SalesTaxTxt:UITextField!
#IBOutlet weak var totalPriceLbl:UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func calculateTotalPrice(_ sender: Any) {
let price = Double(priceTxt.text!)!
let salesTax = Double(SalesTaxTxt.text!)!
let totalSalesTax = price * salesTax
let totalPrice = price + totalSalesTax
totalPriceLbl.text = "$\(totalPrice)"
}
}
I am building a UITableView populated with images and GIFs downloaded using SDWebImage. The images are shown in the table cells, whereas the GIF are shown as a 3D touch preview.
The problem is that every time a GIF is previewed the memory spikes (as expected) however the memory use increases far more than I thought it would. Downloading one of the GIFs manually, I found that it's only around 500kB, but when doing it in the app through SDWebImage, sethe memory increase is closer to 100MB.
After just a few GIF previews the app crashes due to memory issues...
At first I thought perhaps the instance of GIFView was not being deallocated when the GIF preview was exited - I checked with '''deinit''' and it does seem to be deallocating.
I also reset the GIFView to '''nil''' in viewDidDisappear but that did not help either.
Looking at the Allocations Instrument, I found that the GIFs are being permanently stored in memory when they are first loaded. This explains why viewing the same GIF again does not increase the memory.
Does anyone see why these GIFs are taking so much memory? I also built a version of the app where all the assets were local and that ran smoothly with no hiccups or memory issues - but surely the GIF sizes should be the same size in both cases?!
If there is no leak and these memory spikes are inevitable, is there any other way of clearing the GIF from memory when it disappears?
Code is below
//model
struct Visualisation: Codable {
var id: Int
let name, info, url_name, tags, imageURL, gifURL: String
}
//3D touch GIF preview
extension ViewController: UIViewControllerPreviewingDelegate {
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard let indexPath = tableView.indexPathForRow(at: location) else { return nil }
let selectedVis = filteredVisualisations[indexPath.row]
let identifier = "GIFViewController"
guard let GIFVC = storyboard?.instantiateViewController(withIdentifier: identifier) as? GIFViewController else { return nil}
GIFVC.selection = selectedVis
GIFVC.preferredContentSize = CGSize(width: 0, height: 190)
return GIFVC
}
//GIFViewController
import UIKit
import SDWebImage
class GIFViewController: UIViewController {
#IBOutlet weak var GIFView: UIImageView!
var selection = visualisations[0]
override func viewDidLoad() {
super.viewDidLoad()
GIFView.sd_setImage(with: URL(string: selection.gifURL))
// Do any additional setup after loading the view.
}
override func viewDidDisappear(_ animated: Bool = true) {
}
deinit {
print("DEALLOCATED GIFViewController class")
}
}
//setting the table cells
class TableViewCell: UITableViewCell {
#IBOutlet weak var ImageView: UIImageView!
#IBOutlet weak var TitleLabel: UILabel!
#IBOutlet weak var InfoLabel: UILabel!
func setCell(visualisation: Visualisation){
ImageView.sd_setImage(with: URL(string: visualisation.imageURL))
TitleLabel.text = visualisation.name
InfoLabel.text = visualisation.info
}
}
Any help would be much appreciated.
P.S. I am sure you've already noticed that I am very new to iOS development... Pardon my 'newbieness'...
import UIKit
import CoreImage
class ViewController: UIViewController {
#IBOutlet weak var personPic: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
personPic.image = UIImage(named: "stupidsonny")
detect()
}
func detect() {
guard let personciImage = CIImage(image: personPic.image!) else { //This line has the error
return
}
Either the personPic outlet isn't connected, or the "stupidsonny" image isn't getting found and loaded. It's hard to tell which since they're both being accessed on the same line.
To help narrow it down, you could put a ! where you load the image:
personPic.image = UIImage(named: "stupidsonny")!
hi im new to SO so i hope i make everything right.... :)
i started some Days ago iOS programming and no i have a problem that drives me crazy!
Here is the code of the class FactBook:
import Foundation
import UIKit
public class FactBook {
var randomNumberForAll: Int!
let factsArray = [
"Ants stretch when they wake up in the morning.",
"Ostriches can run faster than horses.",
"Olympic gold medals are actually made mostly of silver.",
"You are born with 300 bones; by the time you are an adult you will have 206.",
"It takes about 8 minutes for light from the Sun to reach Earth.",
"Some bamboo plants can grow almost a meter in just one day.",
"The state of Florida is bigger than England.",
"Some penguins can leap 2-3 meters out of the water.",
"On average, it takes 66 days to form a new habit.",
"Mammoths still walked the earth when the Great Pyramid was being built.",
"You can finish the entire FunFacts iOS app course in the time it takes to set up the emulator for the Android course"
]
let imagesArray = [
UIImage(named: "ants.jpg"),
UIImage(named: "ostriches.jpg"),
UIImage(named: "olymp.jpg"),
UIImage(named: "bones.jpg"),
UIImage(named: "light.jpg"),
UIImage(named: "bamboo.jpg"),
UIImage(named: "florida.jpg"),
UIImage(named: "penguins.jpg"),
UIImage(named: "habit.jpg"),
UIImage(named: "mammoth.jpg")
]
func randomFact() ->String {
//Count
var arrayCount = UInt32(factsArray.count)
//Random Number from count
var unsignedRandomNumber = arc4random_uniform(arrayCount)
//Random Number as Int
var randomNumber = Int(unsignedRandomNumber)
self.randomNumberForAll = randomNumber
return factsArray[randomNumber]
}
func randomImage() -> UIImage {
var imageRandom = randomNumberForAll
return imagesArray[imageRandom]!
}
}
Here is the ViewController:
import UIKit
class ViewController: UIViewController {
//Lable, Structs etc.----------------------------------NEU----------------------------
#IBOutlet weak var funFactLable: UILabel!
#IBOutlet weak var funFactButton: UIButton!
#IBOutlet weak var imageView: UIImageView!
let colorWheel = ColorWheel()
var counter = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Loads first Label Text
funFactLable.text = "An interestig Fun Fact comes with one push!"
funFactButton.setTitle("For the first Fun Fact - Push!", forState: UIControlState.Normal)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//ACTIONS-------------------------------------------------------------------------------------
#IBAction func showFunFact() {
var randomColor = colorWheel.randomColor()
var randomImage = FactBook.randomImage()
var randomFact = FactBook.randomFact()
counter++
//BackgroundColor change
view.backgroundColor = randomColor
//Button-TextColor change
funFactButton.tintColor = randomColor
//Button-Title = Counter + Text
funFactButton.setTitle("\(counter). Fun Fact", forState: UIControlState.Normal)
//fadeIn fadeOut FactLable
self.funFactLable.fadeOut(completion: {
(finished: Bool) -> Void in
self.funFactLable.text = randomFact
self.funFactLable.fadeIn()
})
//fadeIn fadeOut ImageView
self.imageView.fadeOut(completion: {
(finished: Bool) -> Void in
self.imageView.image = randomImage
self.imageView.fadeIn()
})
}
}
so the problem is, i cant call the functions (randomFact and randomImage) in the ViewController.
But always the Error Missing argument for parameter #1 in call comes up.
When i change the class factbook to struct i can call the funcĀ“s but then the self.randomNumberForAll doesnt work.
What i just want is to use the randomnumber from the func randomFact() in the func randomImage()....
Thank you if u can help me :) !!!!
I hope this isn't a case of the blind trying to lead the blind as I'm new to swift, but I took this course too recently and was playing around with the code similarly to you. Seems like loading in the Factbook like you did Colorwheel should eliminate your missing parameter error. Unlike the colorwheel though, maybe it has to be a variable instead of a constant, so that you can store and change your randomFactForAll:
let colorWheel = ColorWheel()
var factBook = FactBook()
little late, hope this helps
Need to add keyword "class" to your functions randomFact() and randomImage() to make them as class functions.
Please check the following question for similar issue.
I have implemented text-to-speech in my app and it works fine with the code I currently use. Basically an algo creates a text, and then if the user clicks on the UIButton the text is being spoken.
Challenge: I want to enable the same UIButton to pause the synthesizer, if the button has already been tapped (i.e. text is currently being spoken) and then resume speaking where it left off, if the button is being tapped again.
I know there are a few functions in the AVFoundation Reference but I am unable to implement them correctly.
Does anyone know how to do this in Swift?
import UIKit
import AVFoundation
#IBOutlet var generatedText: UILabel!
#IBAction func buttonSpeakClicked(sender: UIButton){
var mySpeechSynthesizer:AVSpeechSynthesizer = AVSpeechSynthesizer()
var mySpeechUtterance:AVSpeechUtterance = AVSpeechUtterance(string:generatedText.text)
mySpeechUtterance.rate = 0.075
mySpeechSynthesizer .speakUtterance(mySpeechUtterance)
}
AVSpeechSynthesizer Class Reference
Have you tried these methods?
- pauseSpeakingAtBoundary: and - continueSpeaking
And these are some properties, (paused and speaking ) that can help you determine the state of the synthesizer.
Code like this should work: mySpeechSynthesizer.pauseSpeakingAtBoundary(AVSpeechBoundary.Immediate)
In Main.storyboard, make two UIElements:
a UITextView from which the text will be read.
a UIButton to play, pause, and resume reading the text.
Create an outlet from the UITextView to the #IBOutlet and an action from the UIButton to the #IBAction in the code below. The following code is a working example, and should be your ViewController.swift:
import UIKit
import AVFoundation
class ViewController: UIViewController {
// Synth object
let synth = AVSpeechSynthesizer()
// Utterance object
var theUtterance = AVSpeechUtterance(string: "")
// Text element that the synth will read from.
#IBOutlet weak var textView: UITextView!
// Function that starts reading, pauses reading, and resumes
// reading when the UIButton is pressed.
#IBAction func textToSpeech(_ sender: UIButton) {
// The resume functionality
if (synth.isPaused) {
synth.continueSpeaking();
}
// The pause functionality
else if (synth.isSpeaking) {
synth.pauseSpeaking(at: AVSpeechBoundary.immediate)
}
// The start functionality
else if (!synth.isSpeaking) {
// Getting text to read from the UITextView (textView).
theUtterance = AVSpeechUtterance(string: textView.text)
theUtterance.voice = AVSpeechSynthesisVoice(language: "en-GB")
theUtterance.rate = 0.5
synth.speak(theUtterance)
}
}
// Standard function
override func viewDidLoad() {
super.viewDidLoad()
}
// Standard function
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Here how you can achieve this
First create a class variable of AVSpeechSynthesizer and initialize it
let synth = AVSpeechSynthesizer()
This is the button click method ( for playing the audio, or pausing it if it is already playing
#IBAction func onAVButtonClicked(_ sender: Any) {
if synth.isSpeaking {
// when synth is already speaking or is in paused state
if synth.isPaused {
synth.continueSpeaking()
}else {
synth.pauseSpeaking(at: AVSpeechBoundary.immediate)
}
}else{
// when synth is not started yet
let string = attrStr.string
let utterance = AVSpeechUtterance(string: string)
utterance.voice = AVSpeechSynthesisVoice(language: "en-US")
synth.speak(utterance)
}
}