在NSOutputStream中写入数据时更新Progressview

时间:2014-12-03 04:10:13

标签: ios

如何在写入数据时使用NSOutputstream异步更新进度视图。我有总长度,我想通过bytesRead更新进度视图。什么是正确的方法来做到这一点。这是我的流代码:

-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode{
    switch (eventCode) {
        case NSStreamEventOpenCompleted: {
            //   self.nsStream = aStream;


        } break;
        case NSStreamEventHasBytesAvailable: {

            NSLog(@"NSStreamEventHasBytesAvailable");
        }break;
        case NSStreamEventHasSpaceAvailable: {

            if (self.data == nil) {
                self.data = [[NSMutableData alloc]init];
            }
            uint8_t *readBytes = (uint8_t *)[self.completeData mutableBytes];
            readBytes += self.byteIndex; // instance variable to move pointer
            int data_len = [self.completeData length];

            unsigned int len = ((data_len - self.byteIndex >= 1024) ?
                                1024 : (data_len-self.byteIndex));
            uint8_t buf[len];
            (void)memcpy(buf, readBytes, len);
            len = [self.outputStream write:(const uint8_t *)buf maxLength:len];
            self.byteIndex += len;
            NSLog(@"SHARE SUCCESSFULLY WITH %d ",self.byteIndex);
            break;
        } break;
        case NSStreamEventErrorOccurred: {
            NSLog(@"NSStreamEventErrorOccurred");
        } break;
        case NSStreamEventEndEncountered:
        {
            [self.outputStream close];
            [self.outputStream removeFromRunLoop:[NSRunLoop currentRunLoop]
                                         forMode:NSDefaultRunLoopMode];

            self.outputStream = nil; // oStream is instance variable
            break;        }   break;
        default: {
            assert(NO);
        } break;
    }

}

和自定义单元格的进度视图

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIndentifier = @"ShareCell";
    ShareCell *shareCell = [self.shareTable dequeueReusableCellWithIdentifier:CellIndentifier];
    shareCell.delegate = self;

    // Progressview in here
    shareCell.progressView
    shareCell.lblTitle.text =[NSString stringWithFormat:@"%d",indexPath.row];
    return shareCell;
}

1 个答案:

答案 0 :(得分:0)

您可以尝试按键值观察。

首先,让你的bytesRead成为Steam阅读器的一个属性。

@property (nonatomic, assign) int bytesRead;

然后为您的读者添加一个监听器。

[streamreader addObserver:listener forKeyPath:@"bytesRead" options:NSKeyValueObservingOptionNew context:NULL];

KeyPath是您的属性的实际名称" bytesRead"。

然后在监听器类中实现此函数:

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

每当您的bytesRead值改变时,都会调用此方法。使用此方法更新进度视图。您可能希望调整更新bytesRead值的频率,以避免过于频繁地更新进度视图。