stringByEvaluatingJavaScriptFromString causing UI freeze - ios

I am calling JavaScript using stringByEvaluatingJavaScriptFromString. I have UISlider and other UI elements working simultaneously. My whole UI freezes when JavaScript call happens. I looked around about this and found out that making
the call asynchronous should solve the problem.
I have tried two approaches:
[webView performSelectorOnMainThread:#selector(stringByEvaluatingJavaScriptFromString:) withObject:func waitUntilDone:NO]
And this:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
dispatch_async(queue, ^{
[webView performSelectorOnMainThread:#selector(stringByEvaluatingJavaScriptFromString:) withObject:func waitUntilDone:NO];
});
But none of this seems to work. My UI still freezes for fraction of a second which is noticeable. What am I missing?

Try this:-
dispatch_async(dispatch_get_main_queue(), ^{
[webView stringByEvaluatingJavaScriptFromString:func];
});

performSelectorOnMainThread: executes on main thread (The thread of UI).
I think error in your JavaScript, the script executes infinitely.

Related

While dispatch_sync(kBgQueue, ^{}); using at background the foreground UI getting freeze at a moment

I have used the
dispatch_sync(kBgQueue, ^{
});
to get response from webservice at background. While getting the response at background the UI getting delay, ie) while typing the on uitextview the keyboard getting freeze at moment.
How to fix this issue?
Thanks in advance..
dispatch_sync will wait for the block to be executed (which is going to take time depending upon the operation). This blocks the main thread where the UI is updated.
In order to get a responsive UI you need to replace dispatch_sync with dispatch_async.
right code:
dispatch_async(kBgQueue, ^{ });
dispatch_sync Submits a block object for execution on a dispatch queue and waits until that block completes.So it will block your main thread.
for move, see this

Going from main thread to background

I have method A that download images and it start it in background. Then it finished, it runs completion block.
I run method A and I in his completion block. I want to know - now I am in main or in background thread?
You can use:
[NSThread isMainThread];
You're probably still in a background thread. As was mentioned you can check if you're in the background using
[NSThread isMainThread]
If you want to switch to the main thread you can use
dispatch_async(dispatch_get_main_queue(), ^{
// do some things here in the main queue
// for example: update UI controls, etc.
});

Calling methods with delays/sleeps in between

I am in the middle of writing a music game for iOS. What I am trying to do is have the computer play a tune, which involves calling a method that plays a sound, pausing, and calling another method that plays a different sound.
So what I am trying to figure out is how to call these methods with delays/sleeps. I have found two ways that are very cumbersome. the first is do use
[self performSelector:#selector(startNotePlay:) withObject:button afterDelay:.5];
[self performSelector:#selector(startNotePlay:) withObject:button afterDelay:2.5];
etc etc...
However this way is very annoying because all the methods are called at once so the delay has to keep into account how long the pauses are and how long the notes before are playing. so a lot of math would need to be done...
The second way is to use sleep, which is much easier.
[self performSelector:#selector(startNotePlay:) withObject:button afterDelay:.5];
sleep(2.0);
[self performSelector:#selector(startNotePlay:) withObject:button afterDelay:1.5];
the problem with this is that sleep shuts down the main thread. So I can't do any UI changes while sleep is happening.
Is there anything that is in between these two? Basically is there anyway to perform sleep without shutting down everything. Or something like, perform this method, then perform that method after X delay?
Thanks for the help,
Gabe
How about performing one selector and then perform the other one INSIDE this one after a delay? that way you know the one is gonna go off after the other one? :)
Otherwise you can maybe execute a method on a certain time using timeIntervalSinceNow
Just based on this information, I would suggest running this code on a background thread. I assume your note playing code is necessarily running on the main thread. You can, more or less, get the timing you're looking for using something like this.
dispatch_queue_t queue = dispatch_queue_create("musicQueue", NULL);
dispatch_async(queue, ^{
dispatch_async(dispatch_get_main_queue() ^{
[self performSelector:#selector(startNotePlay:) withObject:button afterDelay:.5];
});
});
dispatch_async(queue, ^{
sleep(2.0f);
});
dispatch_async(queue, ^{
dispatch_sync(dispatch_get_main_queue() ^{
[self performSelector:#selector(startNotePlay:) withObject:button afterDelay:1.5];
});
});
There are undoubtedly better ways to accomplish your goal, but without more information, i.e. source code, it's hard to provide a better solution.

dispatch_sync inside a dispatch_async

I just wanted to confirm why this is needed.
I added this code to the KIImagePager (a cocoapod) to load images that are local to the app (the default code loads images from a url).
Here's my working code based off what a coworker suggested:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
dispatch_sync(dispatch_get_main_queue(), ^{
[imageView setImage:[UIImage imageNamed:[aImageUrls objectAtIndex:i]]];;
});
});
I noticed that if I take out the inner dispatch_sync, it works but not in the way I want (some of the images on the image pager scrollview aren't loaded yet when I start scrolling). But they do eventually load.
My question is this, does the sync call on the main queue get the image back to the UI (which is on the main queue)? Because it does work with the second async removed.
The internal dispatch executes its code block on the main thread. This is required because all UI operations must be performed on the main thread. And you're image downloading code (context in which this snippet is executed) may be on a background thread.
The external dispatch executes its block on a background thread. The block its given is the one that executes on the main thread. Thus, the external block can be safely removed.
Hrs an outline of the idiom you're using.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
// do blocking work here outside the main thread.
// ...
// call back with result to update UI on main thread
//
// what is dispatch_sync? Sync will cause the calling thread to wait
// until the bloc is executed. It is not usually needed unless the background
// background thread wants to wait for a side effect from the main thread block
dispatch_sync(dispatch_get_main_queue(), ^{
// always update UI on main thread
});
});
You should only work with UI objects on the main thread. If you don't, you will run into a couple of problems. The first, as you saw, is that UI objects will be delayed in updating. The second is that the app could crash if you try to change UI objects simultaneously from multiple threads. You should only work with UI objects on the main thread.

UIWebView stringByEvaluatingJavaScriptFromString hangs on iOS5.0/5.1 when called using GCD

I have the following code in viewDidLoad, which works properly on iOS 4.3, but it hangs on iOS 5/5.1. On iOS 5/5.1, the alert dialog is shown but can not be dismissed, the UI thread freezes, the OK button just can not be clicked.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_sync(dispatch_get_main_queue(), ^{
[self.webview stringByEvaluatingJavaScriptFromString:#"alert('HELLO WORLD!')"];
});
});
Is this a bug?
After test, I consider it as a Bug, and changing code to use
[webView performSelectorOnMainThread:#selector(stringByEvaluatingJavaScriptFromString:) withObject:js waitUntilDone:NO]
will solve it.
Try it in - (void)viewDidAppear:(BOOL)animated instead
Why are you using GCD at all here?
Remember that in GCD there is no guarantee which thread your code will called on, regardless of queue. My guess is that your DISPATCH_QUEUE_PRIORITY_DEFAULT code happens to be running on the main thread, which is then triggering a deadlock on your dispatch_sync() call. This could be verified by examining your thread states in the debugger or Instruments.
Which gets back to my original question: what do you get by doing these convolutions instead of just calling the method directly on the main thread? You are going to block either way.
You can also change your dispatch_sync() to dispatch_async() - that should also suppress a deadlock, but should only be done if you have other concurrency needs and don't need a background thread to block.
Try
dispatch_async(dispatch_get_main_queue(), ^{
[self.webview stringByEvaluatingJavaScriptFromString:#"alert('HELLO WORLD!')"];
});

Resources