当我的应用进入后台模式时,我有一个被调用的功能。如果用户重新打开应用,我想停止该线程。到目前为止,我没有尝试过任何工作。
到目前为止,这是我的代码:
class Neversleep {
private static var callback : (()->Void)?
private static var thread: NSThread?
static func start(callback: ()->Void) {
self.callback = callback
Neversleep.thread = NSThread(target: self, selector: #selector(Neversleep.task), object: nil)
Neversleep.thread?.start()
}
static func stop() {
print("NEVERSLEEP:STOP")
Neversleep.thread?.cancel()
}
@objc static func task() {
while (true)
{
sleep(3);
print("we are still running!")
callback?()
}
}
}
我从app Delegate的DidEnterBackground方法调用Neversleep.start()。
我从willEnterForeground调用Neversleep.stop()但是它没有停止该线程。
我确定我在这里遗漏了一些明显的东西。但是什么?
答案 0 :(得分:1)
在线程上调用task
并不会自动终止该线程。线程的实际主体需要在其线程被取消时停止它正在做的事情。
更新您的@objc static func task() {
while (!NSThread.currentThread.cancelled)
{
sleep(3);
print("we are still running!")
callback?()
}
}
功能,如下所示:
currentThread
仔细检查cancelled
和callback
的实际方法和属性名称。我不能100%确定它们在Swift 2中的名称。
即使有了上述内容,由于sleep
线程被取消后,您可能会再次拨打@objc static func task() {
while (!NSThread.currentThread.cancelled)
{
sleep(3);
print("we are still running!")
if (!NSThread.currentThread.cancelled) {
callback?()
}
}
}
。您可以通过以下方式解决此问题:
<?xml version="1.0" encoding="utf-8"?>
<KeyedSnapshot xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SnapshotId>2</SnapshotId>
<OperatorStatePerKey>
<Item>
<Key>
<string> user1</string>
</Key>
<Value>
<anyType xsi:type="xsd:string">"<?xml version="1.0" encoding="utf-16"?>
<SerializableDictionaryOfStringBoolean>
<Item>
<Key>
<string> user1</string>
</Key>
<Value>
<boolean>true</boolean>
</Value>
</Item>
</SerializableDictionaryOfStringBoolean>"</anyType>
</Value>
</Item>
<Item>
<Key>
<string> user12</string>
</Key>
<Value>
<anyType xsi:type="xsd:string">"<?xml version="1.0" encoding="utf-16"?>
<SerializableDictionaryOfStringBoolean>
<Item>
<Key>
<string> user12</string>
</Key>
<Value>
<boolean>true</boolean>
</Value>
</Item>
</SerializableDictionaryOfStringBoolean>"</anyType>
</Value>
</Item>
<Item>
<Key>
<string> user10</string>
</Key>
<Value>
<anyType xsi:type="xsd:string">"<?xml version="1.0" encoding="utf-16"?>
<SerializableDictionaryOfStringBoolean>
<Item>
<Key>
<string> user10</string>
</Key>
<Value>
<boolean>true</boolean>
</Value>
</Item>
</SerializableDictionaryOfStringBoolean>"</anyType>
</Value>
</Item>
</OperatorStatePerKey>
</KeyedSnapshot>