即使在按下主页按钮时我处于后台,我也想继续计时。我该怎么做?
这是我的工作代码,它是锻炼的计时器。计数完成后我正在使用闹钟:
import UIKit
import AVFoundation
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
var pickerInfo: [String] = []
var tempsCuisson:Int = 0
var timer:Timer = Timer()
var lecteur:AVAudioPlayer = AVAudioPlayer()
var estActif:Bool = false
var selection:Int?
//outlets
@IBOutlet weak var minuteurLabel: UILabel!
override func viewDidAppear(_ animated: Bool) {
minuteurLabel.text = minuteurString(temps: tempsCuisson)
}
@IBOutlet weak var activerMinuteurBtn: UIButton!
@IBOutlet weak var pickerView: UIPickerView!
@IBOutlet weak var navBar: UINavigationBar!
//actions
@IBAction func activerMinuteurAction(_ sender: UIButton) {
compteur()
}
@IBAction func resetMinuteurAction(_ sender: UIButton) {
resetCompteur()
}
override func viewDidLoad() {
super.viewDidLoad()
//datasource + delegate
pickerView.dataSource = self
pickerView.delegate = self
pickerInfo = ["00.15", "00.30", "00:45",
"01:00", "01:15", "01:30", "01:45",
"02:00", "02:15", "02:30", "02:45",
"03:00", "03:15", "03:30", "03:45",
"04:00", "04:15", "04:30", "04:45",
"05:00", "05:15", "05:30", "05:45",
"06:00", "06:15", "06:30", "06:45",
"07:00", "07:15", "07:30", "07:45",
"08:00", "08:15", "08:30", "08:45",
"09:00", "09:15", "09:30", "09:45", "10:00"
]
activerMinuteurBtn.setTitleColor(UIColor.white, for: UIControlState.normal)
activerMinuteurBtn.isEnabled = false
activerMinuteurBtn.alpha = 0.3
alarm()
}
func selectionCuisson(selection: Int) {
var titreVC:String?
switch selection {
case 0:
//code
tempsCuisson = 015
minuteurLabel.text = minuteurString(temps: tempsCuisson)
navBar.topItem?.title = titre(str: pickerInfo[selection])
break
case 1:
//code
tempsCuisson = 030
minuteurLabel.text = minuteurString(temps: tempsCuisson)
navBar.topItem?.title = titre(str: pickerInfo[selection])
break
case 2:
//code
tempsCuisson = 045
minuteurLabel.text = minuteurString(temps: tempsCuisson)
navBar.topItem?.title = titre(str: pickerInfo[selection])
break
case 3:
//code
tempsCuisson = 060
minuteurLabel.text = minuteurString(temps: tempsCuisson)
navBar.topItem?.title = titre(str: pickerInfo[selection])
break
all cases...
default:
//code
print("Aucune sélection")
break
}
//pour afficher option sélectionnée dans barre navigation
//self.title = titreVC
activerMinuteurBtn.isEnabled = true
activerMinuteurBtn.alpha = 1
minuteurLabel.textColor = UIColor.black
}
func minuteurString(temps: Int) -> String {
let minutes = Int(temps) / 60 % 60
let secondes = Int(temps) % 60
return String(format: "%02i:%02i", minutes, secondes)
}
func compteur() {
if (!estActif) {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.incrementer), userInfo: nil, repeats: true)
timer.fire()
activerMinuteurBtn.setTitle("STOP", for: UIControlState.normal)
activerMinuteurBtn.setTitleColor(UIColor.orange, for: UIControlState.normal)
estActif = true
} else {
timer.invalidate()
activerMinuteurBtn.setTitle("Démarrer", for: UIControlState.normal)
activerMinuteurBtn.setTitleColor(UIColor.blue, for: UIControlState.normal)
estActif = false
}
}
func incrementer() {
if (tempsCuisson == 0) {
timer.invalidate()
minuteurLabel.text = "00:00"
activerMinuteurBtn.setTitle("Démarrer", for: UIControlState.normal)
activerMinuteurBtn.setTitleColor(UIColor.blue, for: UIControlState.normal)
minuteurLabel.textColor = UIColor.green
activerMinuteurBtn.isEnabled = false
activerMinuteurBtn.alpha = 0.3
lecteur.play()
} else {
tempsCuisson -= 1
minuteurLabel.text = minuteurString(temps: tempsCuisson)
}
}
func resetCompteur() {
timer.invalidate()
tempsCuisson = 0
minuteurLabel.text = "00:00"
activerMinuteurBtn.setTitle("Démarrer", for: UIControlState.normal)
activerMinuteurBtn.setTitleColor(UIColor.white, for: UIControlState.normal)
estActif = false
activerMinuteurBtn.isEnabled = false
activerMinuteurBtn.alpha = 0.3
pickerView.selectRow(0, inComponent: 0, animated: true)
}
//AVAudioPlayer
func alarm() {
DispatchQueue.global(qos: .userInitiated).async {
let fichier = Bundle.main.path(forResource: "alarm", ofType: "mp3")
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient, with:[.duckOthers])
try AVAudioSession.sharedInstance().setActive(true)
try self.lecteur = AVAudioPlayer(contentsOf: (URL(string: fichier!))!)
} catch {
print("erreur lecture ficher MP3")
}
}
}
//Retourner Titre
func titre(str:String) -> String {
return str
}
//MARK - PickerViewDataSource
// returns the number of 'columns' to display.
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
// returns the # of rows in each component..
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerInfo.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickerInfo[row]
}
//changer couleur pickerView label
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: pickerView.frame.size.width, height: 44))
label.textColor = UIColor.white
label.font = UIFont(name: "HelveticaNeue-Bold", size: 22)
label.textAlignment = .center
label.text = String(format:" %@", pickerInfo[row])
if (row == selection) {
label.textColor = UIColor.yellow
}
return label
}
//MARK - PickerViewDelegate
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
selectionCuisson(selection: row)
selection = row
}
}
最佳答案
好吧,无需深入研究您的代码,您似乎正在使用 Timer.scheduledTimer 每秒手动递减用户设置的时间。
正如您所发现的那样,这不是一项好技术 - 只有当您知道您可以绝对控制应用程序的时间时,它才有效。
相反,您应该做的是存储用户启动警报的时间、预计的结束时间,并运行计时器以定期更新 UI。
(我的代码在这里并不完美,但它应该为您指明正确的方向,以解决让计时器在后台运行的问题。)
例如
class ViewController: UIViewController {
// this is pseudo-code as I don't have my compiler open :(
let start: Date!
let end: Date!
func selectionCuisson(selection: Int) {
...
start = Date()
end = Date(timeInterval: tempsCuisson, since: start)
}
}
然后您创建一个计时器,它只会更新 UI。
// You can set this to be faster than the increment, for a smoother UI experience
// put in compteur()? I think
timer = Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(ViewController.incrementer), userInfo: nil, repeats: true)
timer.fire()
...
func incrementer() {
let tempsCuisson = end - start
if tempsCuisson < 0 {
// End your Timing Function here
timer.invalidate()
...
lecteur.play()
} else {
minuteurLabel.text = minuteurString(temps: tempsCuisson)
}
}
您还可以使用 end 日期将本地通知设置为在应用程序进入后台时关闭
// when the app becomes inactive
let notification = UILocalNotification()
...
notification.fireDate = end
UIApplication.shared.scheduleLocalNotification(notification)
关于ios - Swift 3 - 如何让我的计时器在后台计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43330907/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack
在选择我想要运行操作的频率时,唯一的选项是“每天”、“每小时”和“每10分钟”。谢谢!我想为我的Rails3.1应用程序运行调度程序。 最佳答案 这不是一个优雅的解决方案,但您可以安排它每天运行,并在实际开始工作之前检查日期是否为当月的第一天。 关于ruby-如何每月在Heroku运行一次Scheduler插件?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/8692687/
我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为
我有一大串格式化数据(例如JSON),我想使用Psychinruby同时保留格式转储到YAML。基本上,我希望JSON使用literalstyle出现在YAML中:---json:|{"page":1,"results":["item","another"],"total_pages":0}但是,当我使用YAML.dump时,它不使用文字样式。我得到这样的东西:---json:!"{\n\"page\":1,\n\"results\":[\n\"item\",\"another\"\n],\n\"total_pages\":0\n}\n"我如何告诉Psych以想要的样式转储标量?解