iOS 5 - AFNetworking - 上传视频

时间:2012-05-08 19:39:04

标签: iphone ios5 upload afnetworking

对于我的应用,用户可以录制视频或从相册中选择视频,并通过php脚本将视频文件上传到服务器。要将文件上传到服务器,我正在使用AFNetworking。我最初试图从相册上传视频,但由于我无法上传,我在主套装中添加了一个视频(我知道通过我为php脚本制作的html前端上传得很好)。

代码是:

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。

是否有任何事情对任何人造成伤害,或者我还缺少其他什么?

提前致谢

2 个答案:

答案 0 :(得分: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];

答案 1 :(得分:4)

也许对象立即被释放。使AFHTTPClient成为您的类的实例变量或将其子类化并使其成为单例。

更重要:替换此行:

[operation start];

使用:

[httpClient enqueueHTTPRequestOperation:operation];