2012-05-08 145 views
2

对于我的应用程序,用户将能够录制视频或从他们的相册中选择视频并通过php脚本将视频文件上传到服务器。要将文件上传到服务器,我正在使用AFNetworking。我最初尝试从相册上传视频,但由于无法工作,我添加了一个视频(我知道通过我为php脚本制作的html前端上传的视频)可以上传到主包中。iOS 5 - AFNetworking - 上传视频

的代码是:

NSString *vidURL = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"mov"]; 
    NSData *videoData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:vidURL]]; 

    NSLog(@"The test vid's url is %@.",vidURL); 

    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL fileURLWithPath: @"http://www.mywebsite.com"]]; 

    NSMutableURLRequest *afRequest = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload.php" parameters:nil constructingBodyWithBlock:^(id <AFMultipartFormData>formData) 
    { 
     [formData appendPartWithFileData:videoData name:@"file" fileName:@"test.mov" mimeType:@"video/quicktime"]; 
    }]; 

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:afRequest]; 

    [operation setUploadProgressBlock:^(NSInteger bytesWritten,long long totalBytesWritten,long long totalBytesExpectedToWrite) 
    { 

     NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite); 

    }]; 

    [operation start]; 

我的PHP脚本运行良好,因为我能够通过HTML表单上传相同的视频。但是,上面的代码无法到达setUploadProgressBlock。

是否有任何东西突破为任何人或有什么我失踪?

在此先感谢

回答

5

这是我用来解决这个问题:

httpClient = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://www.mysite.com"]]; 

    NSMutableURLRequest *afRequest = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload.php" parameters:nil constructingBodyWithBlock:^(id <AFMultipartFormData>formData) 
    { 
     [formData appendPartWithFileData:videoData name:@"file" fileName:@"filename.mov" mimeType:@"video/quicktime"]; 
    }]; 


    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:afRequest]; 

    [operation setUploadProgressBlock:^(NSInteger bytesWritten,long long totalBytesWritten,long long totalBytesExpectedToWrite) 
    { 

     NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite); 

    }]; 

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {NSLog(@"Success");} 
             failure:^(AFHTTPRequestOperation *operation, NSError *error) {NSLog(@"error: %@", operation.responseString);}]; 
    [operation start]; 
4

也许对象正在立即取消分配。使AFHTTPClient成为您的类的实例变量或子类,并使其成为单例。

更重要:替换此行:

[operation start]; 

有:

[httpClient enqueueHTTPRequestOperation:operation]; 
+0

只是好奇,为什么你会使用[ httpClient enqueueHTTPRequestOperation:operation] over [operation start]?大部分AFNetworking的调用[操作开始]。此外,仍然获得操作响应的空返回值。 – Will

+1

好的,[操作开始]也应该可以,但为什么不使用AFHTTPClient的NSOperationQueue?这会自动调度请求的执行并且更适合并发操作。注意这两个都是错误的。 – Felix