[英]I want to add MBProgressHUD in NSObject class
我正在从我的NSObject类在服务器上上传数据,现在我想在上传数据时显示MBProgressHUD,我知道如何使用ViewController显示MBProgressHUD,但不知道如何通过NSObject类显示。
AppDelegate* delegate = [[UIApplication sharedApplication] delegate];
[delegate.window addSubview:HUD];
...
[HUD removeFromSuperview];
有几种解决此类问题的方法。 尽管可以使用块,KVO或通知,但是最常见的一种是使用委托模式。
您应该首先创建一个协议,以便可以在UIViewController
和进行调用的NSObject
之间进行通信。 尽管您不需要创建该通信,但应该使用它来获得更灵活的代码。
通常,我会这样做:
@protocol CommunicationDelegate <NSObject>
@required
-(void)communicationSucceed;
-(void)communicationFailedWithError:(NSError*)anError;
在您的NSObject
内部,对于符合协议CommunicationDelegate
的对象,您将拥有weak
引用。 在您的.h文件中,您应具有以下内容:
@property(nonatomic, weak) id <CommunicationDelegate> communicationDelegate;
在实际开始使用NSObject
,您应该执行以下操作:
myObjectThatWillDoSomething.communicationDelegate = self;
目前,您的UIViewController
和NSObject
之间具有有效的引用。 在您的UIViewController的.h文件中,添加以下内容:
@interface myViewController : UIViewController <CommunicationDelegate>
因此,您的UIViewController
符合CommunicationDelegate
协议。
现在,您可以从UIViewController
启动MBProgressHUD
。 NSObject
完成工作后,您可以调用:
[communicationDelegate communicationSucceed];
要么
[communicationDelegate communicationFailedWithError:anError]; //anError is used to describe what went wrong
一旦调用了这些方法之一,就可以删除MBProgressHUD
。 了解此方法在UIViewController
内部调用。
当您上传NSObject时,会显示一个视图,对吗? 因此,在该视图中显示HUD。 您可能需要创建一个委托,以在下载开始,结束时以及出现错误时通知视图。
使用NSNotification Center停止指示器,在视图控制器中用监听方法声明NSNotification。 并从Webservice文件中发布通知。 通知中心监听方法中的停止指示器。
此链接将为您提供帮助
在您的上传器对象上创建委托协议
@protocol UploaderThingyDelegate <NSObject>
-(void)stuffStarted;
-(void)stuffEnded;
@end
@interface UploaderThingy : NSObject
@property (weak) id<UploaderThingyDelegate> delegate;
将相关的View或ViewController设置为上载者委托,并触发MBProgressHUD在此处添加/删除。
这些下面的代码在NSObject文件中工作正常
步骤1:下载 https://github.com/jdg/MBProgressHUD
步骤2:添加代理MBProgressHUDDelegate
步骤3:声明实例MBProgressHUD * HUD;
步骤4:在需要的地方编写代码:
HUD = [[MBProgressHUD alloc] initWithWindow:[UIApplication sharedApplication].keyWindow];
[[UIApplication sharedApplication].keyWindow addSubview:HUD];
HUD.delegate = self;
HUD.labelText = @"Processing";
[HUD show:YES];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.