Swift alternative to performSelectorOnMainThread - swift

I want to reload my table data inside a block in this method:
import UIKit
import AssetsLibrary
class AlbumsTableViewController: UITableViewController {
var albums:ALAssetsGroup[] = []
func loadAlbums(){
let library = IAAssetsLibraryDefaultInstance
library.enumerateGroupsWithTypes(ALAssetsGroupType(ALAssetsGroupAll),
usingBlock: {(group, stop) in
if group {
self.albums.append(group)
}
else {
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
}, failureBlock: { (error:NSError!) in println("Problem loading albums: \(error)") })
}
override func viewDidLoad() {
super.viewDidLoad()
loadAlbums()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
//self.navigationItem.rightBarButtonItem = self.editButtonItem
}
But the else block will not execute. The error I get is:
'performSelectorOnMainThread' is unavailable: 'performSelector' methods are unavailable
So what is the alternative to 'performSelectorOnMainThread' in swift?
UPDATE:
I am now getting an abort error.

This simple C-function:
dispatch_async(dispatch_get_main_queue(), {
// DO SOMETHING ON THE MAINTHREAD
self.tableView.reloadData()
})
What about launching your function with:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
loadAlbums()
})
in viewDidLoad()?

Swift 3
DispatchQueue.main.async(execute:
{
//Code to execute on main thread
})

Use GCD in lieu of performSelector variations.
dispatch_async(dispatch_get_main_queue()) {
() -> Void in
self.doSomething()
}

You are calling performSelectorOnMainThread on UIViewController instead of UITableView's object
May be your code:
self.performSelectorOnMainThread(Selector(reloadData), withObject: self.tblMainTable, waitUntilDone: true)
Instead of:
self.tblMainTable.performSelectorOnMainThread(Selector("reloadData"), withObject: nil, waitUntilDone: true)
you are getting that message because UIViewController does't have any method named "performSelectorOnMainThread"

//Xcode 8.2 // swift 3.0
I am accessing an API which gives the data regarding weather i.e 'temperature', 'humidity', 'pressure' etc after submitting the name or zipcode of any city.
So, That data need to be shown(It must be on Main Thread) on UI (the tableView)
self.performSelector(onMainThread: #selector(Home.DataOnUI), with: nil, waitUntilDone: true)
//
func DataOnUI() {
self.tblView.reloadData()
}
P.S. Home is the class of UIViewController

Swift 3 / Xcode 8.2
Here is a Swift 3 way of doing things. Simply insert the time (in seconds) that you would like the code to execute after.
let delayTime = DispatchTime.now() + Double(Int64(20.0 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime) {
//Your code to run after 20 seconds
}
Alternatively you could simply place your time delay in one-line notation like so:
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
// Your code to run after 10 seconds
}

Related

After my completion handler completes still unable to re-load tableView data swift 4

In my model i've got a function to read in data from firebase.
I call completionHandler(true) when that's done.
This is my viewDidLoad function in my controller that extends UITableViewController.
override func viewDidLoad()
{
super.viewDidLoad()
let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
tableView.backgroundView = activityIndicatorView
self.activityIndicatorView = activityIndicatorView
activityIndicatorView.startAnimating()
model.readInFirebaseData { (success) in
print("data read in")
activityIndicatorView.stopAnimating()
dataArray = model.firebaseDataArray
self.tableView.reloadData()
}
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
tableView.tableHeaderView = searchController.searchBar
}
But the table remains empty and for whatever reason self.tableView.reloadData() isn't populating the table as i'd like but if I segue from the TableViewController and come back the list is populated.
I can't see exactly where i'm going wrong.
Thanks.
Update:
I still couldn't get it working so instead of a completionHandler i used a delegate. What i did was:
Singleton:
protocol Refresh{
func refreshData()
}
var delegate:Refresh?
func readInFirebaseData()
{
self.ref.child("users").observe(DataEventType.childAdded, with: { (snapshot) in
user.name = value?["name"] as? String ?? ""
self.dict.updateValue(user, forKey: uid)
DispatchQueue.main.async {
self.delegate?.refreshData()
print("main thread dispatch")
}
})
}
The TableViewController:
class ListController: TableViewController, Refresh{
viewDidLoad()
{
model.delegate = self
}
func refreshData() {
print("called")
array = model.array
self.tableView.reloadData()
}
That all works. The only issue really that I don't know the answer to is the DispatchQueue.main.async is getting called everytime firebase reads in a "user". But I put it at the end of the readInFirebase function and nothing was populated on the list. But in any case it works at the moment.
Probably readInFirebaseData method is asynchronous and the callback runs on a thread different from the main one.
Remember that all the UIKit related calls must be run on the main thread.
Try with:
model.readInFirebaseData { (success) in
print("data read in")
dataArray = model.firebaseDataArray
DispatchQueue.main.async {
activityIndicatorView.stopAnimating()
self.tableView.reloadData()
}
}
Be sure to set delegate and dataSource:
tableView.delegate = self
tableView.dataSource = self
And make sure you call reloadData() from Main Thread:
DispatchQueue.main.async {
self.tableView.reloadData()
}
Calling it from background threads would typically not lead to your table reloaded, since this operation is UI-related. Any UI related operations should be performed from main thread.

How do I run an asynchronous thread that only runs as long as the view that uses it is presented?

How do I run an asynchronous thread that only runs as long as the view that uses it is presented?
I want the view to run this asynchronous thread. However, as soon as the view disappears, I want that thread to stop running. What's the best way to do this? I'm not sure where to start and might be thinking about this the wrong way. Nevertheless, what I described is how I want it to behave to the user.
You can use NSOperation to achieve what you want, NSOperation and NSOperationQueue are built on top of GCD. As a very general rule, Apple recommends using the highest-level abstraction, and then dropping down to lower levels when measurements show they are needed.
For example, You want to download images asynchronously when the view is loaded and cancel the task when the view is disappeared. First create a ImageDownloader object subclass to NSOperation. Notice that we check if the operation is cancelled twice, this is because the NSOperation has 3 states: isReady -> isExecuting -> isFinish and when the operation starts executing, it won't be cancelled automatically, we need to do it ourself.
class ImageDownloader: NSOperation {
//1
var photoRecord: NSURL = NSURL(string: "fortest")!
//2
init(photoRecord: NSURL) {
self.photoRecord = photoRecord
}
//3
override func main() {
//4
if self.cancelled {
return
}
//5
let imageData = NSData(contentsOfURL:self.photoRecord)
//6
if self.cancelled {
return
}
}
}
Then you can use it like: downloader.cancel(), downloader.start(). Notice that we need to check if the operation is cancelled in the completion block.
import UIKit
class ViewController: UIViewController {
let downloder = ImageDownloader(photoRecord: NSURL(string: "test")!)
override func viewDidLoad() {
super.viewDidLoad()
downloder.completionBlock = {
if self.downloder.cancelled {
return
}
print("image downloaded")
}
//Start the task when the view is loaded
downloder.start()
}
override func viewWillDisappear(animated: Bool) {
//Cancel the task when the view will disappear
downloder.cancel()
}
}
Once DetailViewController is presented, the asyncOperation method will be executed asynchronously.
Note: currently the asyncOperation method is executed every second so if you want the method to be called only once, you must change the repeats property to false.
class DetailViewController: UIViewController {
// timer that will execute
// asynchronously an operation
var timer: NSTimer!
// counter used in the async operation.
var counter = 0
// when view is about to appear
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// setting up the timer
timer = NSTimer.scheduledTimerWithTimeInterval(
1.0,
target: self,
selector: #selector(asyncOperation),
userInfo: nil,
repeats: true //set up false if you don't want the operation repeats its execution.
)
}
// when view is about to disappear
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
// stopping the timer
timer.invalidate()
}
// async operation that will
// be executed
func asyncOperation() {
counter += 1
print("counter: \(counter)")
}
}
Source: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/
Result:

How to stop a DispatchWorkItem in GCD?

I am currently playing around with Grand Central Dispatch and discovered a class called DispatchWorkItem. The documentation seems a little incomplete so I am not sure about using it the right way. I created the following snippet and expected something different. I expected that the item will be cancelled after calling cancel on it. But the iteration continues for some reason. Any ideas what I am doing wrong? The code seems fine for me.
#IBAction func testDispatchItems() {
let queue = DispatchQueue.global(attributes:.qosUserInitiated)
let item = DispatchWorkItem { [weak self] in
for i in 0...10000000 {
print(i)
self?.heavyWork()
}
}
queue.async(execute: item)
queue.after(walltime: .now() + 2) {
item.cancel()
}
}
GCD does not perform preemptive cancelations. So, to stop a work item that has already started, you have to test for cancelations yourself. In Swift, cancel the DispatchWorkItem. In Objective-C, call dispatch_block_cancel on the block you created with dispatch_block_create. You can then test to see if was canceled or not with isCancelled in Swift (known as dispatch_block_testcancel in Objective-C).
func testDispatchItems() {
let queue = DispatchQueue.global()
var item: DispatchWorkItem?
// create work item
item = DispatchWorkItem { [weak self] in
for i in 0 ... 10_000_000 {
if item?.isCancelled ?? true { break }
print(i)
self?.heavyWork()
}
item = nil // resolve strong reference cycle of the `DispatchWorkItem`
}
// start it
queue.async(execute: item!)
// after five seconds, stop it if it hasn't already
queue.asyncAfter(deadline: .now() + 5) {
item?.cancel()
item = nil
}
}
Or, in Objective-C:
- (void)testDispatchItem {
dispatch_queue_t queue = dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0);
static dispatch_block_t block = nil; // either static or property
__weak typeof(self) weakSelf = self;
block = dispatch_block_create(0, ^{
for (long i = 0; i < 10000000; i++) {
if (dispatch_block_testcancel(block)) { break; }
NSLog(#"%ld", i);
[weakSelf heavyWork];
}
block = nil;
});
// start it
dispatch_async(queue, block);
// after five seconds, stop it if it hasn't already
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
if (block) { dispatch_block_cancel(block); }
});
}
There is no asynchronous API where calling a "Cancel" method will cancel a running operation. In every single case, a "Cancel" method will do something so the operation can find out whether it is cancelled, and the operation must check this from time to time and then stop doing more work by itself.
I don't know the API in question, but typically it would be something like
for i in 0...10000000 {
if (self?.cancelled)
break;
print(i)
self?.heavyWork()
}
DispatchWorkItem without DispatchQueue
let workItem = DispatchWorkItem{
//write youre code here
}
workItem.cancel()// For Stop
DispatchWorkItem with DispatchQueue
let workItem = DispatchWorkItem{
//write youre code here
}
DispatchQueue.main.async(execute: workItem)
workItem.cancel()// For Stop
Execute
workItem.perform()// For Execute
workItem.wait()// For Delay Execute

How to delete the action inside closure after using dispatch_after function? [duplicate]

I want to run a block of code in 10 seconds from an event, but I want to be able to cancel it so that if something happens before those 10 seconds, the code won't run after 10 seconds have gone by.
I've been using this, but it's not cancellable:
static func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure
)
}
How can I accomplish this?
Swift 3 has DispatchWorkItem:
let task = DispatchWorkItem { print("do something") }
// execute task in 2 seconds
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2, execute: task)
// optional: cancel task
task.cancel()
Update for Swift 3.0
Set Perform Selector
perform(#selector(foo), with: nil, afterDelay: 2)
foo method will call after 2 seconds
func foo()
{
//do something
}
To cancel pending method call
NSObject.cancelPreviousPerformRequests(withTarget: self)
Try this (Swift 2.x, see David's answer below for Swift 3):
typealias dispatch_cancelable_closure = (cancel : Bool) -> ()
func delay(time:NSTimeInterval, closure:()->()) -> dispatch_cancelable_closure? {
func dispatch_later(clsr:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(time * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), clsr)
}
var closure:dispatch_block_t? = closure
var cancelableClosure:dispatch_cancelable_closure?
let delayedClosure:dispatch_cancelable_closure = { cancel in
if let clsr = closure {
if (cancel == false) {
dispatch_async(dispatch_get_main_queue(), clsr);
}
}
closure = nil
cancelableClosure = nil
}
cancelableClosure = delayedClosure
dispatch_later {
if let delayedClosure = cancelableClosure {
delayedClosure(cancel: false)
}
}
return cancelableClosure;
}
func cancel_delay(closure:dispatch_cancelable_closure?) {
if closure != nil {
closure!(cancel: true)
}
}
// usage
let retVal = delay(2.0) {
println("Later")
}
delay(1.0) {
cancel_delay(retVal)
}
From Waam's comment here: dispatch_after - GCD in swift?
You need to do this:
class WorkItem {
private var pendingRequestWorkItem: DispatchWorkItem?
func perform(after: TimeInterval, _ block: #escaping VoidBlock) {
// Cancel the current pending item
pendingRequestWorkItem?.cancel()
// Wrap the request in a work item
let requestWorkItem = DispatchWorkItem(block: block)
pendingRequestWorkItem = requestWorkItem
DispatchQueue.main.asyncAfter(deadline: .now() + after, execute:
requestWorkItem)
}
}
// Use
lazy var workItem = WorkItem()
private func onMapIdle() {
workItem.perform(after: 1.0) {
self.handlePOIListingSearch()
}
}
References
Link swiftbysundell
Link git
This should work:
var doIt = true
var timer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: Selector("doSomething"), userInfo: nil, repeats: false)
//you have now 10 seconds to change the doIt variable to false, to not run THE CODE
func doSomething()
{
if(doIt)
{
//THE CODE
}
timer.invalidate()
}
I use #sas 's method in some projects, somehow this doesn't work anymore, maybe something changed after Swift 2.1.1. value copy instead of pointer?
the easiest work around method for me is:
var canceled = false
delay(0.25) {
if !canceled {
doSomething()
}
}
For some reason, NSObject.cancelPreviousPerformRequests(withTarget: self) was not working for me. A work around I thought of was coming up with the max amount of loops I'd allow and then using that Int to control if the function even got called.
I then am able to set the currentLoop value from anywhere else in my code and it stops the loop.
//loopMax = 200
var currentLoop = 0
func loop() {
if currentLoop == 200 {
//do nothing.
} else {
//perform loop.
//keep track of current loop count.
self.currentLoop = self.currentLoop + 1
let deadline = DispatchTime.now() + .seconds(1)
DispatchQueue.main.asyncAfter(deadline: deadline) {
//enter custom loop parameters
print("i looped")
self.loop()
}
}
and then elsewhere in your code you can then
func stopLooping() {
currentLoop = 199
//setting it to 199 allows for one last loop to happen. You can adjust based on the amount of loops you want to be able to do before it just stops. For instance you can set currentLoop to 195 and then implement a fade animation while loop is still happening a bit.
}
It's really quite dynamic actually. For instance you can see if currentLoop == 123456789, and it will run infinitely (pretty much) until you set it to that value somewhere else in your code. Or you can set it to a String() or Bool() even, if your needs are not time based like mine were.

Go to another view when NSURLSession finishes its job

My problem is when I try to go another view after some api call finishes, it wont go to the next view. Here is the code below. Thanks in advance.
var task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: {
(data, response, error) in //println(response)
//println(error)
self.myWeather.apiCallData = JSON(data: data)
self.myWeather.apiCallError = error
println("api call finished")
if error == nil {
println("no error")
let weatherView = self.storyboard?.instantiateViewControllerWithIdentifier("WeatherView") as WeatherViewController
weatherView.myWeather = self.myWeather
self.navigationController?.pushViewController(weatherView, animated: false)
}
}).resume()
It does print api call finished and no error on console. But it doesn't go to the other scene.
The problem is that the completion handler code of the dataTaskWithURL method runs in a background secondary thread, not in the main thread (where view controller transition can happen).
Wrap the call to pushViewController in a main thread queue closure:
...
dispatch_async(dispatch_get_main_queue(), {
let navigationVC = self.navigationController
navigationVC?.pushViewController(weatherView, animated: false)
})
...
I have written the code in two lines to avoid a swift compiler bug (single statement and closure return value: see this). You can also write it as:
...
dispatch_async(dispatch_get_main_queue(), {
(self.navigationController)?.pushViewController(weatherView, animated: false)
return
})
...