从ALAsset获取视频

Ric*_*lli 12 iphone alasset alassetslibrary

使用iOS 4中提供的新资产库框架,我看到我可以使用UIImagePickerControllerReferenceURL获取给定视频的URL.返回的url采用以下格式:

assets-library://asset/asset.M4V?id=1000000004&ext=M4V
Run Code Online (Sandbox Code Playgroud)

我正在尝试将此视频上传到网站,以便快速证明我正在尝试以下内容

NSData *data = [NSData dataWithContentsOfURL:videourl];
[data writeToFile:tmpfile atomically:NO];
Run Code Online (Sandbox Code Playgroud)

在这种情况下,数据永远不会初始化.有没有人设法通过新资产库直接访问网址?谢谢你的帮助.

zou*_*oul 22

我使用以下类别ALAsset:

static const NSUInteger BufferSize = 1024*1024;

@implementation ALAsset (Export)

- (BOOL) exportDataToURL: (NSURL*) fileURL error: (NSError**) error
{
    [[NSFileManager defaultManager] createFileAtPath:[fileURL path] contents:nil attributes:nil];
    NSFileHandle *handle = [NSFileHandle fileHandleForWritingToURL:fileURL error:error];
    if (!handle) {
        return NO;
    }

    ALAssetRepresentation *rep = [self defaultRepresentation];
    uint8_t *buffer = calloc(BufferSize, sizeof(*buffer));
    NSUInteger offset = 0, bytesRead = 0;

    do {
        @try {
            bytesRead = [rep getBytes:buffer fromOffset:offset length:BufferSize error:error];
            [handle writeData:[NSData dataWithBytesNoCopy:buffer length:bytesRead freeWhenDone:NO]];
            offset += bytesRead;
        } @catch (NSException *exception) {
            free(buffer);
            return NO;
        }
    } while (bytesRead > 0);

    free(buffer);
    return YES;
}

@end
Run Code Online (Sandbox Code Playgroud)


Ric*_*lli 17

这不是最好的方法.我正在回答这个问题,以防另一个SO用户遇到同样的问题.

基本上我的需要是能够将视频文件假脱机到tmp文件,以便我可以使用ASIHTTPFormDataRequest将其上传到网站.可能有一种从资产网址流式传输到ASIHTTPFormDataRequest上传的方法,但我无法理解.相反,我编写了以下函数将文件删除到tmp文件以添加到ASIHTTPFormDataRequest.

+(NSString*) videoAssetURLToTempFile:(NSURL*)url
{

    NSString * surl = [url absoluteString];
    NSString * ext = [surl substringFromIndex:[surl rangeOfString:@"ext="].location + 4];
    NSTimeInterval ti = [[NSDate date]timeIntervalSinceReferenceDate];
    NSString * filename = [NSString stringWithFormat: @"%f.%@",ti,ext];
    NSString * tmpfile = [NSTemporaryDirectory() stringByAppendingPathComponent:filename];

    ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
    {

        ALAssetRepresentation * rep = [myasset defaultRepresentation];

        NSUInteger size = [rep size];
        const int bufferSize = 8192;

        NSLog(@"Writing to %@",tmpfile);
        FILE* f = fopen([tmpfile cStringUsingEncoding:1], "wb+");
        if (f == NULL) {
            NSLog(@"Can not create tmp file.");
            return;
        }

        Byte * buffer = (Byte*)malloc(bufferSize);
        int read = 0, offset = 0, written = 0;
        NSError* err;
        if (size != 0) {
            do {
                read = [rep getBytes:buffer
                          fromOffset:offset
                              length:bufferSize 
                               error:&err];
                written = fwrite(buffer, sizeof(char), read, f);
                offset += read;
            } while (read != 0);


        }
        fclose(f);


    };


    ALAssetsLibraryAccessFailureBlock failureblock  = ^(NSError *myerror)
    {
        NSLog(@"Can not get asset - %@",[myerror localizedDescription]);

    };

    if(url)
    {
        ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease];
        [assetslibrary assetForURL:url 
                       resultBlock:resultblock
                      failureBlock:failureblock];
    }

    return tmpfile;
}
Run Code Online (Sandbox Code Playgroud)


Gil*_*vik 10

你去......

AVAssetExportSession* m_session=nil;

-(void)export:(ALAsset*)asset withHandler:(void (^)(NSURL* url, NSError* error))handler
{
    ALAssetRepresentation* representation=asset.defaultRepresentation;
    m_session=[AVAssetExportSession exportSessionWithAsset:[AVURLAsset URLAssetWithURL:representation.url options:nil] presetName:AVAssetExportPresetPassthrough];
    m_session.outputFileType=AVFileTypeQuickTimeMovie;
    m_session.outputURL=[NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"%f.mov",[NSDate timeIntervalSinceReferenceDate]]]];
    [m_session exportAsynchronouslyWithCompletionHandler:^
     {
         if (m_session.status!=AVAssetExportSessionStatusCompleted)
         {
             NSError* error=m_session.error;
             m_session=nil;
             handler(nil,error);
             return;
         }
         NSURL* url=m_session.outputURL;
         m_session=nil;
         handler(url,nil);
     }];
}
Run Code Online (Sandbox Code Playgroud)

如果要重新编码电影,可以使用其他预设键(AVAssetExportPresetMediumQuality例如)


小智 9

这是一个干净利落的快速解决方案,可以将视频作为NSData.它使用Photos框架,因为从iOS9开始不推荐使用ALAssetLibrary:

重要

从iOS 9.0开始,不推荐使用Assets Library框架.相反,请使用Photos框架,在iOS 8.0及更高版本中,它可以为用户的照片库提供更多功能和更好的性能.有关更多信息,请参阅照片框架参考.

import Photos

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    self.dismissViewControllerAnimated(true, completion: nil)

    if let referenceURL = info[UIImagePickerControllerReferenceURL] as? NSURL {
        let fetchResult = PHAsset.fetchAssetsWithALAssetURLs([referenceURL], options: nil)
        if let phAsset = fetchResult.firstObject as? PHAsset {
            PHImageManager.defaultManager().requestAVAssetForVideo(phAsset, options: PHVideoRequestOptions(), resultHandler: { (asset, audioMix, info) -> Void in
                if let asset = asset as? AVURLAsset {
                    let videoData = NSData(contentsOfURL: asset.URL)

                    // optionally, write the video to the temp directory
                    let videoPath = NSTemporaryDirectory() + "tmpMovie.MOV"
                    let videoURL = NSURL(fileURLWithPath: videoPath)
                    let writeResult = videoData?.writeToURL(videoURL, atomically: true)

                    if let writeResult = writeResult where writeResult {
                        print("success")
                    }
                    else {
                        print("failure")
                    }
                }
            })
        }
    }
}
Run Code Online (Sandbox Code Playgroud)