如何在文件上传时更新UIProgressView

时间:2015-02-26 09:56:34

标签: ios objective-c progress-bar progress

我想在将文件上传到服务器时显示UIProgressView。因此,我正在编写自定义视图(BlurBg)。它包含UILabelUITextfieldUIProgressView。我正在动态创建它们。这是工作。但进度条没有更新。我知道我必须更新主线程中的进度条,但我不知道我该怎么做。这是我的代码。

当我触摸按钮时,它正在调用[self startTheBackgroundJob]

- (void)startTheBackgroundJob {
    BlurBG *bg = [[BlurBG alloc]init];
    [bg showAlert:self];
    [self performSelectorOnMainThread:@selector(startIt:) withObject:bg waitUntilDone:NO];
}

-(void)startIt:(BlurBG*)bg{
    [bg ProgressUpdate];
}

BlurBG.h

#import <UIKit/UIKit.h>
@interface BlurBG : UIViewController
- (void)showAlert:(UIViewController *)vc;
-(void) ProgressUpdate ;
@end

BlurBG.m

#import "BlurBG.h"
#import "UIImage+ImageEffects.h"
#import <AVFoundation/AVFoundation.h>

#define UIColorFromRGB(rgbValue) [UIColor \
colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

#define SYSTEM_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)

#define KEYBOARD_HEIGHT 80
#define PREDICTION_BAR_HEIGHT 40

@interface BlurBG ()
@property (nonatomic, strong) UIImageView *backgroundView;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIButton *OkBtn;
@property UIProgressView *prog;
@property (nonatomic) CGFloat backgroundOpacity;
@property UILabel *labelTitle;
@property UITextView *viewText;
@end

@implementation BlurBG

CGFloat kWindowWidth;
CGFloat kWindowHeight;
CGFloat kTextHeight;
CGFloat kSubTitleHeight;

#pragma mark - Initialization

- (id)initWithCoder:(NSCoder *)aDecoder
{
    @throw [NSException exceptionWithName:NSInternalInconsistencyException
                               reason:@"NSCoding not supported"
                             userInfo:nil];
}

-(instancetype) init{
    self = [super init];
    if (self)
    {
        kWindowWidth = [UIScreen mainScreen].bounds.size.width-50;
        kWindowHeight = ([UIScreen mainScreen].bounds.size.height/5);

        _OkBtn = [[UIButton alloc] initWithFrame:CGRectMake(kWindowWidth-25,5,20,20)];
        _OkBtn.backgroundColor=[UIColor grayColor];
        [_OkBtn setTitle:@"X" forState:UIControlStateNormal];
        _OkBtn.layer.cornerRadius = 1;
        _OkBtn.clipsToBounds = YES;
        [_OkBtn addTarget:self action:@selector(fadeOut) forControlEvents:UIControlEventTouchUpInside];

        _prog = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
        _prog.progressTintColor=[UIColor colorWithRed:187.0/255 green:160.0/255 blue:209.0/255 alpha:1.0];
        [[_prog layer]setCornerRadius:10.0f];
        [[_prog layer]setBorderWidth:2.0f];
        [[_prog layer]setMasksToBounds:TRUE];
        _prog.clipsToBounds = YES;
       [_prog.layer setBorderColor:[UIColor redColor].CGColor];

        _labelTitle = [[UILabel alloc] init];
        _viewText = [[UITextView alloc] init];
        _contentView = [[UIView alloc] init];

        [self.view addSubview:_contentView];

        [_contentView addSubview:_labelTitle];
        [_contentView addSubview:_viewText];
        [_contentView addSubview:_prog];
        [_contentView addSubview:_OkBtn];

    // Content View
        _contentView.layer.cornerRadius = 5.0f;
        _contentView.layer.masksToBounds = YES;
        _contentView.layer.borderWidth = 0.5f;

        _labelTitle.numberOfLines = 1;
        _labelTitle.textAlignment = NSTextAlignmentCenter;
        _labelTitle.font = [UIFont fontWithName:@"HelveticaNeue" size:20.0f];

        // View text
        _viewText.editable = NO;
        _viewText.allowsEditingTextAttributes = YES;
        _viewText.textAlignment = NSTextAlignmentCenter;
        _viewText.font = [UIFont fontWithName:@"HelveticaNeue" size:14.0f];

        _backgroundView = [[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];
        _backgroundView.userInteractionEnabled = YES;

        _contentView.backgroundColor = [UIColor whiteColor];
        _labelTitle.textColor = UIColorFromRGB(0x4D4D4D);
        _viewText.textColor = UIColorFromRGB(0x4D4D4D);
        _contentView.layer.borderColor = UIColorFromRGB(0xCCCCCC).CGColor;

    }
    return self;
}

-(void) ShowTitle:(UIViewController *)vc{
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    self.view.alpha = 0;
    [self makeBlurBackground];
    _backgroundView.frame = vc.view.bounds;
    _labelTitle.text = @"Title";
    _viewText.text = @"Description..";
    [window addSubview:_backgroundView];
    [window addSubview:self.view];
    [vc addChildViewController:self];
    [self fadeIn];
}

- (void)showAlert:(UIViewController *)vc {
    [self ShowTitle:vc];
}

-(void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];

    CGSize sz = [UIScreen mainScreen].bounds.size;

    if (SYSTEM_VERSION_LESS_THAN(@"8.0"))
    {
        if UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation])
        {
            CGSize ssz = sz;
            sz = CGSizeMake(ssz.height, ssz.width);
        }
    }

    CGRect newFrame = self.backgroundView.frame;
    newFrame.size = sz;
    self.backgroundView.frame = newFrame;

    CGRect r;
    if (self.view.superview != nil)
    {
        r = CGRectMake((sz.width-kWindowWidth)/2, (sz.height-kWindowHeight)/2, kWindowWidth, kWindowHeight/2);
    }
    else
    {
        r = CGRectMake((sz.width-kWindowWidth)/2, -kWindowHeight, kWindowWidth, kWindowHeight);
    }

    self.view.frame = r;

    _contentView.frame = CGRectMake(0,0, kWindowWidth, kWindowHeight);
    _labelTitle.frame = CGRectMake((kWindowWidth-(kWindowWidth-10))/2, 5, kWindowWidth-10,28);
    _viewText.frame = CGRectMake((kWindowWidth-(kWindowWidth-10))/2, 8+(_labelTitle.frame.size.height), kWindowWidth-10,28);
    _prog.frame = CGRectMake((kWindowWidth-(kWindowWidth-10))/2, 65, kWindowWidth-10,28);
}

- (void)fadeIn
{
    self.backgroundView.alpha = 0.0f;
    self.view.alpha = 0.0f;

    [UIView animateWithDuration:0.3f
                      delay:0.0f
                    options:UIViewAnimationOptionCurveEaseIn
                 animations:^{
                     self.backgroundView.alpha = _backgroundOpacity;
                     self.view.alpha = 1.0f;
                 }
                 completion:^(BOOL completed){
                     //[self performSelectorOnMainThread:@selector(ProgressAyarla) withObject:nil waitUntilDone:YES];
                 }];
}


- (void)fadeOut
{
    [UIView animateWithDuration:0.3f animations:^{
        self.backgroundView.alpha = 0.0f;
        self.view.alpha = 0.0f;
    } completion:^(BOOL completed) {
        [self.backgroundView removeFromSuperview];
        [self.view removeFromSuperview];
        [self removeFromParentViewController];
    }];
}

- (void)makeBlurBackground
{
    UIImage *image = [UIImage convertViewToImage];
    UIImage *blurSnapshotImage = [image applyBlurWithRadius:5.0f
                                              tintColor:[UIColor colorWithWhite:0.2f
                                                                          alpha:0.7f]
                                  saturationDeltaFactor:1.8f
                                              maskImage:nil];

    _backgroundView.image = blurSnapshotImage;
    _backgroundView.alpha = 0.0f;
    _backgroundOpacity = 1.0f;
}

-(void) ProgressUpdate {
    for (int i=0; i<100; i++) {
        [NSThread sleepForTimeInterval:0.3];
        float currentProgress = _prog.progress;
        NSLog(@"%i",i);
        [_prog setProgress:currentProgress+1.0 animated:YES];
    };
}

@end

2 个答案:

答案 0 :(得分:3)

请问这个代码吗?

        dispatch_queue_t queue = dispatch_queue_create("your-app-name", NULL);
    dispatch_async(queue, ^{
        //Create your BlurBG Class.
        BlurBG *bg = [[BlurBG alloc]init];
        [bg showAlert:self];

        dispatch_async(dispatch_get_main_queue(), ^{
            //Update UI
            [bg ProgressUpdate];
        });
    });

答案 1 :(得分:2)

通常我使用这种方法在主线程中对UI元素执行某些操作,以防止排队操作到队列末尾。 dispatch_async在主线程中立即执行操作,如果我是正确的。

__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_main_queue(), ^{
    __strong typeof(weakSelf) strongSelf = weakSelf;
    if (strongSelf) {
        [strongSelf.prog setProgress:currentProgress + 1.f animated:YES]; 
    }
});