【问题标题】:Upload with Buffer iOS 7使用缓冲区 iOS 7 上传
【发布时间】:2014-05-16 20:54:49
【问题描述】:

我正在尝试使用随机数据实现上传并测量速度。现在我正在像这样生成我的随机 NSData:

void * bytes = malloc("");
NSData * myData = [NSData dataWithBytes:bytes length:"bytes"];
free("bytes");

但是如果我想上传一个大文件会有内存问题...

我的上传过程是这样的:

NSURLSessionConfiguration *sessionConfig =
[NSURLSessionConfiguration defaultSessionConfiguration];

NSURLSession *session =
[NSURLSession sessionWithConfiguration:sessionConfig
                              delegate:self
                         delegateQueue:nil];

NSURL * urll = [NSURL URLWithString:UPLOAD_SERVER];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:urll];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest addValue:@"Keep-Alive" forHTTPHeaderField:@"Connection"];

NSString *boundary = @"*****";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[urlRequest addValue:contentType forHTTPHeaderField: @"Content-Type"];

NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[urlRequest setHTTPBody:body];

void * bytes = malloc(250000000);
NSData * uploadData = [NSData dataWithBytes:bytes length:250000000];
free(bytes);

ulTask = [session uploadTaskWithRequest:urlRequest fromData:uploadData];

[ulTask resume];

有没有办法用缓冲区或其他东西上传?!比如生成小数据,上传这个然后生成一个新的再上传?!

【问题讨论】:

  • @Rob 这正是我的意思...你有 NSInputStream 类的例子吗?!
  • 参见 BJ Homer 关于Subclassing NSInputStreamNSURLSessionNSURLConnection 的文章。我已将相关位合并到我的答案中,如下所示。
  • 毫无疑问,如果要继承 NSInputStream,请从 BJ Homer 的文章开始。也就是说,确保你需要,这不是微不足道的。

标签: ios iphone ios7 upload nsurlsessionuploadtask


【解决方案1】:
-(void) updateUserData:(NSDictionary*)data
     withImageToUpload:(NSData*)imageToUpload
               success: (void (^) (id responseObject))success
               failure: (void (^)(NSError* error))failure
{
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"PATCH"
                                                                                              URLString:@"URL_REQUEST/update_profile"
                                                                                             parameters:data
                                                                              constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
                                    {
                                        [formData appendPartWithFileData:imageToUpload
                                                                    name:@"individual[avatar]"
                                                                fileName:@"avatar.jpg"
                                                                mimeType:@"image/jpeg"];
                                    }

                                                                                                  error:nil];

    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSProgress *progress = nil;

    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request
                                                                       progress:&progress
                                                              completionHandler:^(NSURLResponse *response, id responseObject, NSError *error)
                                          {
                                              if (error)
                                              {
                                                  NSLog(@"Error: %@", error);
                                                  failure(error);
                                              } else
                                              {
                                                  [[NSNotificationCenter defaultCenter] postNotificationName:@"userDataDidUpdated" object:self];
                                                  success(responseObject);
                                              }
                                          }];

    [uploadTask resume];

}

【讨论】:

  • 多部分示例对我很有用。
【解决方案2】:

我建议开始上传并继续发送数据。您还可以通过使用 uploadTaskWithStreamedRequest 来避免创建 250mb 缓冲区,然后创建一个 NSInputStream 子类,它只会不断提供更多数据,直到您告诉它停止。您可以实现URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend: 来监控上传进度(因此您可以大概监控数据发送的速度)。

无论如何,创建上传请求:

@interface ViewController () <NSURLSessionDelegate, NSURLSessionTaskDelegate>

@property (nonatomic, strong) CustomStream *inputStream;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.inputStream = [[CustomStream alloc] init];

    NSURL *url = [NSURL URLWithString:kURLString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];

    NSURLSessionUploadTask *task = [session uploadTaskWithStreamedRequest:request];

    [task resume];

    // I don't know how you want to finish the upload, but I'm just going 
    // to stop it after 10 seconds

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.inputStream.finished = YES;
    });
}

您显然必须实现适当的委托方法:

#pragma mark - NSURLSessionTaskDelegate

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
{
    NSLog(@"%lld %lld %lld", bytesSent, totalBytesSent, totalBytesExpectedToSend);
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task needNewBodyStream:(void (^)(NSInputStream *bodyStream))completionHandler
{
    completionHandler(self.inputStream);
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    NSLog(@"%s: error = %@; data = %@", __PRETTY_FUNCTION__, error, [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding]);
}

#pragma mark - NSURLSessionDataDelegate

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
{
    self.responseData = [NSMutableData data];
    completionHandler(NSURLSessionResponseAllow);
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    [self.responseData appendData:data];
}

还有CustomStream

static NSInteger const kBufferSize = 32768;

@interface CustomStream : NSInputStream

@property (nonatomic, readonly) NSStreamStatus streamStatus;
@property (nonatomic, getter = isFinished) BOOL finished;

@end

@interface CustomStream ()

@property (nonatomic) NSStreamStatus streamStatus;
@property (nonatomic) void *buffer;

@end

@implementation CustomStream

- (instancetype)init
{
    self = [super init];
    if (self) {
        _buffer = malloc(kBufferSize);
        NSAssert(_buffer, @"Unable to create buffer");
        memset(_buffer, 0, kBufferSize);
    }
    return self;
}

- (void)dealloc
{
    if (_buffer) {
        free(_buffer);
        self.buffer = NULL;
    }
}

- (void)open
{
    self.streamStatus = NSStreamStatusOpen;
}

- (void)close
{
    self.streamStatus = NSStreamStatusClosed;
}

- (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)len
{
    if ([self isFinished]) {
        if (self.streamStatus == NSStreamStatusOpen) {
            self.streamStatus = NSStreamStatusAtEnd;
        }
        return 0;
    }

    NSUInteger bytesToCopy = MIN(len, kBufferSize);
    memcpy(buffer, _buffer, bytesToCopy);

    return bytesToCopy;
}

- (BOOL)getBuffer:(uint8_t **)buffer length:(NSUInteger *)len
{
    return NO;
}

- (BOOL)hasBytesAvailable
{
    return self.streamStatus == NSStreamStatusOpen;
}

- (void)scheduleInRunLoop:(__unused NSRunLoop *)aRunLoop
                  forMode:(__unused NSString *)mode
{}

- (void)removeFromRunLoop:(__unused NSRunLoop *)aRunLoop
                  forMode:(__unused NSString *)mode
{}

#pragma mark Undocumented CFReadStream Bridged Methods

- (void)_scheduleInCFRunLoop:(__unused CFRunLoopRef)aRunLoop
                     forMode:(__unused CFStringRef)aMode
{}

- (void)_unscheduleFromCFRunLoop:(__unused CFRunLoopRef)aRunLoop
                         forMode:(__unused CFStringRef)aMode
{}

- (BOOL)_setCFClientFlags:(__unused CFOptionFlags)inFlags
                 callback:(__unused CFReadStreamClientCallBack)inCallback
                  context:(__unused CFStreamClientContext *)inContext {
    return NO;
}

@end

我建议您参考 BJ Homer 的文章 Subclassing NSInputStream,了解有关此 NSInputStream 子类中一些神秘方法的一些背景知识。

【讨论】:

  • ViewController的声明怎么不需要定义主类?
  • .h 文件中,我ViewController 定义为UIViewController(或其他)子类。但是在.m 文件中,我有一个私有类扩展(@interface ViewController ())来定义不属于公共.h 文件的私有属性。不过,我只是没有费心在此处包含 .h 文件,因为它与手头的问题并不真正相关。
  • 感谢您的回答和有用的评论。如果我想使用ViewController 来控制后端的上传,我应该从什么子类化它?假设我在didSendBodyData 中调用someProgressCallback 函数,在didCompleteWithError 中调用someResultCallback 函数。
  • 从什么子类化视图控制器 (VC) 只是 UI 的一个问题。通常是UIViewController,但也可能是UITableViewControllerUICollectionViewController。无论您的 UI 需要什么。但你真正的问题是你应该把这些委托方法放在哪里。坦率地说,我通常会避免将它们放在一些大型视图控制器中,而是创建一个专用的网络管理器,一个 NSObject 子类并将委托方法放在那里。然后VC可以提供someProgressCallbacksomeResultCallback块给这个网络管理器。
猜你喜欢
  • 1970-01-01
  • 2020-05-14
  • 2013-09-28
  • 2012-05-03
  • 1970-01-01
  • 2012-07-08
  • 2013-11-30
  • 1970-01-01
  • 2012-06-07
相关资源
最近更新 更多