如何从磁盘

时间:2016-04-22 18:09:31

标签: ios nsdata

给出这样的网址:

file:///private/var/mobile/Applications/C133BAE7-0CBC-4E4F-826B-509B5E1EB68E/tmp/uzhMyDkL0mSI-SCVideo-Merged.mov

如何将NSData表示形式发送到服务器?我已经尝试了所有这些:

NSData *videoData = [NSData dataWithContentsOfURL:url];
NSData *videoData = [NSData dataWithContentsOfFile:[url absoluteString]];
NSData *videoData = [[NSFileManager defaultManager] contentsAtPath:[url path]];

videoData每次都是零。

编辑: 对于更多上下文,我尝试使用SCRecorder来捕获视频。

- (void)recorder:(SCRecorder *__nonnull)recorder didCompleteSegment:(SCRecordSessionSegment *__nullable)segment inSession:(SCRecordSession *__nonnull)session error:(NSError *__nullable)error {

    [session mergeSegmentsUsingPreset:AVAssetExportPresetHighestQuality completionHandler:^(NSURL *url, NSError *error) {
        if (error == nil) {
            //NSData *videoData = [NSData dataWithContentsOfURL:url];
            //NSData *videoData = [NSData dataWithContentsOfFile:[url absoluteString]];
            NSData *videoData = [[NSFileManager defaultManager] contentsAtPath:[url path]];

        } else {
            NSLog(@"Bad things happened: %@", error);
        }
    }];

}

2 个答案:

答案 0 :(得分:1)

文件URL对我来说是正确的但是要确定,在尝试获取NSData之前应该添加此方法:

NSError *error = nil;
if ([url checkResourceIsReachableAndReturnError: &error] == FALSE)
{
    NSLog(@"URL %@ is not available because %@", [url absoluteString], [error localizedDescription]);
}

您还可以尝试通过以下方式获取文件:

NSError *error = nil;
NSData *videoData = [NSData dataWithContentsOfURL:url
                              options: NSDataReadingUncached
                                error:&error];
if (videoData == nil)
{
    NSLog(@"URL %@ is not available because %@", [url absoluteString], [error localizedDescription]);
} else {
    // you've likely got data, since videoData is not nil!
}

答案 1 :(得分:0)

这很奇怪,但是如果我这样做的话就可以了:

- (void)recorder:(SCRecorder *__nonnull)recorder didCompleteSegment:(SCRecordSessionSegment *__nullable)segment inSession:(SCRecordSession *__nonnull)session error:(NSError *__nullable)error {

    [session mergeSegmentsUsingPreset:AVAssetExportPresetHighestQuality completionHandler:^(NSURL *url, NSError *error) {
        if (error == nil) {
            [self getDataFromUrl:url];
        } else {
            NSLog(@"Bad things happened: %@", error);
        }
    }];

}

- (void)getDataFromUrl:(NSURL *)url {
    NSError *error = nil;
    NSData *videoData = [NSData dataWithContentsOfURL:url
                                              options:NSDataReadingUncached
                                                error:&error];
    if (videoData == nil)
    {
        NSLog(@"URL %@ is not available because %@", [url absoluteString], [error localizedDescription]);
    } else {
        NSLog(@"GOT IT");
    }
}

videoData现在是有效的NSData。如果分成不同的方法,可以解释为什么会这样做?