in my app I am implementing my internet network with global dispatch queue and gcd.
I want to set network indicator visible while there is network activity.
here is my network block - >
{
[[UIApplication sharedApplication]setNetworkActivityIndicatorVisible:YES];
send sync http request
[[UIApplication sharedApplication]setNetworkActivityIndicatorVisible:NO];
}
my questions :
I want to check if there is a block that doesn't executed yet! before hiding network indicator. How could I implement that !
does calling setNetworkActivityIndicatorVisible from another thread, safe because i see that NetworkActivityIndicatorVisible is nonatomic.
#DavidBemerguy's approach is a good start, but you'd typically want to implement it with dispatch_group_notify to hide your indicator. That said, IMO, you don't need GCD here. You just need a NetworkIndicatorController.
Create an object (the controller) that listens to notifications like DidStartNetworkActivity and DidStopNetworkActivity. Post notifications when you start or stop. Inside the controller, keep a count and when it hits 0, hide the indicator. Something like this (totally untested, just typing here, and I've been writing exclusively in Swift for the last few days, so forgive any missing semicolons):
.h:
extern NSString * const DidStartNetworkActivityNotification;
extern NSString * const DidStopNetworkActivityNotification;
#interface NetworkIndicatorController
- (void) start;
- (void) stop;
#end
.m
#interface NetworkIndicatorController ()
#property (nonatomic, readwrite, assign) NSInteger count;
#end
#implementation NetworkIndicatorController
- (void)start {
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self name:DidStartNetworkActivityNotification selector:#selector(didStart:) object:nil];
[nc addObserver:self name:DidStopNetworkActivityNotification selector:#selector(didStop:) object:nil];
self.count = 0;
}
- (void)stop {
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc removeObserver:self name:DidStartNetworkActivityNotification object:nil];
[nc removeObserver:self name:DidStopNetworkActivityNotification object:nil];
}
- (void)didStart:(NSNotification *)note {
dispatch_async(dispatch_get_main_queue(), {
self.count = self.count + 1;
[[UIApplication sharedApplication]setNetworkActivityIndicatorVisible:YES];
});
}
- (void)didStop:(NSNotification *)note {
dispatch_async(dispatch_get_main_queue(), {
self.count = self.count - 1;
if (self.count <= 0) {
[[UIApplication sharedApplication]setNetworkActivityIndicatorVisible:NO];
}
});
}
You could get similar stuff with dispatch_group, but I think this is simpler. The problem with the dispatch group approach is keeping track of when you do and don't want to call dispatch_notify. I'm sure the final code isn't that hard, but it's trickier to think about all the possible race conditions.
You could also just directly call -startNetworkActivity and -stopNetworkActivity directly on an instance of this object that you pass around rather than using notifications.
One possible approach is to create a group of tasks, then waiting for them to finish. Between the start and finish you can update your activity indicator. Obviously you'll need some object that will retain reference to the group. Check this code, based on apple documentation:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); // Retain this queue somewhere accessible from the places you want to dispatch
dispatch_group_t group = dispatch_group_create(); // Retain this group somewhere accessible from the places you want to dispatch
// Add a task to the group
dispatch_group_async(group, queue, ^{
// Some asynchronous work
});
// Do some other work while the tasks execute.
disptach_sync(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication]setNetworkActivityIndicatorVisible:YES];
}
// When you cannot make any more forward progress,
// wait on the group to block the current thread.
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
// Release the group when it is no longer needed.
disptach_sync(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication]setNetworkActivityIndicatorVisible:NO];
}
dispatch_release(group);
Remember that you can have a singleton object that you dispatch your blocks and and keeps track of your wait.
Related
In my iOS application, I am posting a NSNotification and catching it in one of my UIView in main thread. I want to pass extra information along with the notification. I was using userInfo dictionary of NSNotification for that.
[[NSNotificationCenter defaultCenter] postNotificationName:#"NotifyValueComputedFromJS" object:self userInfo:#{#"notificationKey":key,#"notificationValue":value,#"notificationColor":color,#"notificationTimeStamp":time}];
key, value, color and time are local variables which contains the value I need to pass. In UIView I am adding observer for this notification and I am using notification.userInfo to get these data
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(receiveNotification:) name:#"NotifyValueComputedFromJS" object:nil];
-(void)receiveNotification:(NSNotification *)notification
{
if ([notification.userInfo valueForKey:#"notificationKey"]!=nil && [[notification.userInfo valueForKey:#"notificationKey"] isEqualToString:self.notificationKey] && [notification.userInfo valueForKey:#"notificationValue"]!=nil) {
[self updateLabelWithValue:[notification.userInfo valueForKey:#"notificationValue"]];
}
}
The frequency in which this notification is posted is 4 times in one second. I am doing some animations also in main thread. The problem I am facing here is my UI is lagging. UI will respond to scroll events or touch events with huge delay(I have faced a delay of even 1 to 2 seconds). After some research I came to know that NSDictionary is bulky and will cause lag if used in main thread. Is there any other way I can pass my data through NSNotification?
I have tried out another way. I have created a custom NSObject class to save the data I want and I am passing it as the object parameter of postNotification method.
[[NSNotificationCenter defaultCenter] postNotificationName:#"NotifyValueComputedFromJS" object:customDataObject userInfo:nil];
Here customDataObject is an instance of my custom NSObject class. I know the parameter is meant to be the sender of notification(usually it will be self). Is it a wrong approach if I am sending a custom object as parameter?
As BobDave mentioned, the key is to send the notification on some thread other than the main UI thread. This can be accomplished with dispatch_async, or with a queue.
The typical pattern for this behavior is sender:
-(void)sendDataToObserver {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:#"NotifyValueComputedFromJS" object:customDataObject userInfo:userInfo:#{#"notificationKey":key,#"notificationValue":value,#"notificationColor":color,#"notificationTimeStamp":time}];
});
}
And receiver (NOTE: weak self because retain cycles):
-(void)addObserver {
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(receiveNotification:) name:#"NotifyValueComputedFromJS" object:nil];
}
-(void)receiveNotification:(NSNotification *)notification {
if ([notification.userInfo valueForKey:#"notificationKey"]!=nil && [[notification.userInfo valueForKey:#"notificationKey"] isEqualToString:self.notificationKey] && [notification.userInfo valueForKey:#"notificationValue"]!=nil) {
__weak typeof (self) weakSelf = self;
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf updateLabelWithValue:[notification.userInfo valueForKey:#"notificationValue"]];
});
}
}
Maybe you could use - addObserverForName:object:queue:usingBlock:
and use a non-main queue to execute the block in order to reduce the lag. Also, shouldn't the observer be added in a UIViewController, not a UIView?
I am trying to use this within a project: https://github.com/zakkhoyt/VWWPermissionKit
I do not understand KVO/Notification Center as much as I'd like so posting a question.
Basically the init and dealloc for the Permission Manager look like this:
- (instancetype)init {
self = [super init];
if (self) {
[[NSNotificationCenter defaultCenter] addObserverForName:VWWPermissionNotificationsPromptAction object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
dispatch_async(dispatch_get_main_queue(), ^{
VWWPermission *permission = note.userInfo[VWWPermissionNotificationsPermissionKey];
[permission presentSystemPromtWithCompletionBlock:^{
dispatch_async(dispatch_get_main_queue(), ^{
[permission updatePermissionStatus];
if(permission.status == VWWPermissionStatusDenied){
[self.permissionsViewController displayDeniedAlertForPermission:permission];
}
[self checkAllPermissionsSatisfied];
});
}];
});
}];
[[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidBecomeActiveNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
dispatch_async(dispatch_get_main_queue(), ^{
[self readPermissions];
});
}];
}
return self;
}
-(void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
If I want to read a set of permissions I would call this:
NSArray *permissionsToRead = #[
[VWWCoreLocationWhenInUsePermission permissionWithLabelText:nil],
[VWWNotificationsPermission permissionWithLabelText:nil]
];
[VWWPermissionsManager readPermissions:permissionsToRead resultsBlock:^(NSArray *permissions) {
// Do something with the result
}
}];
This all works fine. The issue is that the dealloc is not being called, therefore the Notifications are still being called such as the UIApplicationDidBecomeActiveNotification being created in the init method.
As far as I can see the Permission Manager is created and not referenced and therefore it just hangs around.
The public method for the readPermssions is as follows:
+(void)readPermissions:(NSArray*)permissions resultsBlock:(VWWPermissionsManagerResultsBlock)resultsBlock{
VWWPermissionsManager *permissionsManager = [[self alloc]init];
[permissionsManager readPermissions:permissions resultsBlock:resultsBlock];
}
A new instance is created and another method is called then passes the resultsBlock back. There is nothing that releases this as far as I can tell. How would I get the dealloc to be called?
It's because NSNotificationCenter is retaining the observer object, which is retaining the block that is registered with it, which is capturing your view controller and preventing it from being deallocated.
If you want your view controller to be able to be released then you should create a weak reference (__weak typeof(self) weakSelf = self;) to it outside the block and use weakSelf inside the block.
You also aren't removing the observer correctly. When you add an observer using the notification center block api it returns an object which is what it is actually adding as the observer and which you need to keep a reference to and pass to removeObserver:.
I would suggest just not using the method to observe with a block since it adds more management trouble than it's worth. Use the one that takes a selector instead.
I have 3 screens on my app.First is login. Second is search and third is process the task.
On login i retrieve data from a web service. It returns data in XML format. So the data is considerably large. So i am doing that task on a background thread like this to stop Mainthread freezing up on me:
-(BOOL)loginEmp
{
.....some computation
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
(unsigned long)NULL), ^(void) {
[self getAllCustomerValues];
});
}
-(void)getAllCustomerValues
{
....more computation.Bring the data,parse it and save it to CoreData DB.
//notification - EDIT
NSNotification *notification =[NSNotification notificationWithName:#"reloadRequest"
object:self];
[[NSNotificationCenter defaultCenter] postNotification : notification];
}
//EDIT
//SearchScreenVC.m
- (void)viewDidLoad
{
....some computation
[self.customerActIndicator startAnimating];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(stopActivityIndicator)
name:#"reloadRequest"
object:nil];
}
- (void)stopActivityIndicator
{
[self.customerActIndicator stopAnimating];
self.customerActIndicator.hidesWhenStopped = YES;
self.customerActIndicator.hidden =YES;
NSLog(#"HIt this at 127");
}
So on condition that login was successful, i move to screen 2. But the background thread is still in process( i know because i have logs logging values) . I want an activity indicator showing up here (2nd screen)telling user to wait before he starts searching. So how do i do it?How can i make my activity indicator listen/wait for background thread. Please let me know if you need more info.Thanks
EDIT: so I edited accordingly but the notification never gets called. I put a notification at the end of getAllCustomerValues and in viewDidLoad of SearchScreen i used it. That notification on 2nd screen to stop animating never gets called. What is the mistake i am doing.?Thanks
EDIT 2: So it finally hits the method. I dont know what made it to hit that method. I put a break point. I wrote to stop animating but it wouldn't. I wrote hidesWhenStoppped and hidden both to YES. But it still keeps animating.How do i get it to stop?
Ok, if it is not the main thread, put the following in and that should fix it.
- (void)stopActivityIndicator
{
if(![NSThread isMainThread]){
[self performSelectorOnMainThread:#selector(stopActivityIndicator) withObject:nil waitUntilDone:NO];
return;
}
[self.customerActIndicator stopAnimating];
self.customerActIndicator.hidesWhenStopped = YES;
self.customerActIndicator.hidden =YES;
NSLog(#"HIt this at 127");
}
Could you put your background operation into a separate class and then set a delegate on it so you can alert the delegate once the operation has completed?
I havent tried this, its just an idea :)
You could use a delegate pointing to your view controller & a method in your view controller like:
- (void) updateProgress:(NSNumber*)percentageComplete {
}
And then in the background thread:
float percentComplete = 0.5; // for example
NSNumber *percentComplete = [NSNumber numberWithFloat:percentComplete];
[delegate performSelectorOnMainThread:#selector(updateProgress:) withObject:percentageComplete waitUntilDone:NO];
In relation to this question I was wondering if there is any generally accepted logic regarding when to use NSNotification, with an observer in your main thread, vs using GCD to dispatch work from a background thread to the main thread?
It seems that with a notification-observer setup you have to remember to tear down the observer when your view unloads but then you reliably ignore the notification, where as dispatching a job to the main thread may result in a block being executed when the view has been unloaded.
As such, it seems to me that notifications should provide improved app stability. I'm assuming that the dispatch option provides better performance from what I've read of GCD?
UPDATE:
I'm aware that notifications and dispatch can work happily together and in some cases, should be used together. I'm trying to find out if there are specific cases where one should/shouldn't be used.
An example case: Why would I select the main thread to fire a notification from a dispatched block rather than just dispatching the receiving function on the main queue? (Obviously there would be some changes to the receiving function in the two cases, but the end result would seem to be the same).
The NSNotificationCenter and gcd & dispatch_get_main_queue() serve very different purposes. I don't thing "vs" is truly applicable.
NSNotificationCenter provides a way of de-coupling disparate parts of your application. For example the kReachabilityChangedNotification in Apple's Reachability sample code is posted to the notification center when the system network status changes. And in turn you can ask the notification center to call your selector/invocation so you can respond to such an event.(Think Air Raid Siren)
gcd on the other hand provides a quick way of assigning work to be done on a queue specified by you. It lets you tell the system the points at which your code can be dissected and processed separately to take advantage of multiple-threads and of multi-core CPUs.
Generally (almost always) the notifications are observed on the thread on which they are posted. With the notable exception of one piece of API...
The one piece of API where these to concepts intersect is NSNotificationCenter's:
addObserverForName:object:queue:usingBlock:
This is essentially a convenient method for ensuring that a given notification is observed on a given thread. Although the "usingBlock" parameter gives away that behind the scenes it's using gcd.
Here is an example of its usage. Suppose somewhere in my code there is an NSTimer calling this method every second:
-(void)timerTimedOut:(NSTimer *)timer{
dispatch_async(dispatch_get_global_queue(0, 0), ^{
// Ha! Gotcha this is on a background thread.
[[NSNotificationCenter defaultCenter] postNotificationName:backgroundColorIsGettingBoringNotification object:nil];
});
}
I want to use the backgroundColorIsGettingBoringNotification as a signal to me to change my view controller's view's background color. But it's posted on a background thread. Well I can use the afore mentioned API to observe that only on the main thread. Note viewDidLoad in the following code:
#implementation NoWayWillMyBackgroundBeBoringViewController {
id _observer;
}
-(void)observeHeyNotification:(NSNotification *)note{
static NSArray *rainbow = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
rainbow = #[[UIColor redColor], [UIColor orangeColor], [UIColor yellowColor], [UIColor greenColor], [UIColor blueColor], [UIColor purpleColor]];
});
NSInteger colorIndex = [rainbow indexOfObject:self.view.backgroundColor];
colorIndex++;
if (colorIndex == rainbow.count) colorIndex = 0;
self.view.backgroundColor = [rainbow objectAtIndex:colorIndex];
}
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor redColor];
__weak PNE_ViewController *weakSelf = self;
_observer = [[NSNotificationCenter defaultCenter] addObserverForName:backgroundColorIsGettingBoringNotification
object:nil
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note){
[weakSelf observeHeyNotification:note];
}];
}
-(void)viewDidUnload{
[super viewDidUnload];
[[NSNotificationCenter defaultCenter] removeObserver:_observer];
}
-(void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:_observer];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
The primary advantage of this API seems to be that your observing block will be called during the postNotification... call. If you used the standard API and implemented observeHeyNotification: like the following there would be no guarantee how long it would be before your dispatch block was executed:
-(void)observeHeyNotification:(NSNotification *)note{
dispatch_async(dispatch_get_main_queue(), ^{
// Same stuff here...
});
}
Of course in this example you could simply not post the notification on a background thread, but this might come in handy if you are using a framework which makes no guarantees about on which thread it will post notifications.
I hope I have better luck with someone helping me on this one:
I have a UIPickerView where a user makes a selection and then presses a button. I can gladly obtain the users choice, as shown in my NSLog, and when this is done, I want to send a notification to another view controller that will show a label with the option selected. Well, although it seems everything is done right, somehow it does not work and the label stays intact. Here is the code:
Broadcaster:
if ([song isEqualToString:#"Something"] && [style isEqualToString:#"Other thing"])
{
NSLog (#"%#, %#", one, two);
[[NSNotificationCenter defaultCenter] postNotificationName:#"Test1" object:nil];
ReceiverViewController *receiver = [self.storyboard instantiateViewControllerWithIdentifier:#"Receiver"];
[self presentModalViewController:receiver animated:YES];
}
Observer:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(receiveNotification) name:#"Test1" object:nil];
}
return self;
}
-(void)receiveNotification:(NSNotification*)notification
{
if ([[notification name] isEqualToString:#"Test1"])
{
[label setText:#"Success!"];
NSLog (#"Successfully received the test notification!");
}
else
{
label.text = #"Whatever...";
}
}
I think you have a syntax error in your selector: #selector(receiveNotification). It should probably be #selector(receiveNotification:) with the colon since your method accepts the NSNotification *notification message. Without it, it's a different signature.
The issue is likely that the notification is sent (and therefore received) on a different thread than the main thread. Only on the main thread will you be able to update UI elements (like a label).
See my answer to this question for some insight into threads and NSNotifications.
Use something like:
NSLog(#"Code executing in Thread %#",[NSThread currentThread] );
to compare your main thread versus where your recieveNotifcation: method is being executed.
If it is the case that you are sending the notification out on a thread that is not the main thread, a solution may be to broadcast your nsnotifications out on the main thread like so:
//Call this to post a notification and are on a background thread
- (void) postmyNotification{
[self performSelectorOnMainThread:#selector(helperMethod:) withObject:Nil waitUntilDone:NO];
}
//Do not call this directly if you are running on a background thread.
- (void) helperMethod{
[[NSNotificationCenter defaultCenter] postNotificationName:#"SOMENAME" object:self];
}
If you only care about the label being updated on the main thread, you can perform that operation on the main thread using something similar to:
dispatch_sync(dispatch_get_main_queue(), ^(void){
[label setText:#"Success!"];
});
Hope that was helpful!