ios - 如何从 iOS/iPhone 中的 Assets 库获取照片/视频源路径?

标签 ios alassetslibrary assetslibrary

我一个多星期以来一直面临这个问题,我无法从 Assets 库 url 获取原始照片/视频路径。

我可以通过将此文件保存到我的应用程序 SandBox 来获取它的数据,但在这里我想避免这种情况再次创建该文件的另一个副本。

我在 DropBox 中投资了这个,他们直接从 Assets 库 url 上传。所以,请帮我解决这个问题。

提前致谢。

这是我的代码:

-(NSString*) videoAssetURLToTempFile:(NSString*)combineURL{
self.activityIndicator.hidden = FALSE;
NSLog(@"combineURL: %@",combineURL);
NSArray *arr = [combineURL componentsSeparatedByString:@"->"];
NSString *index = [arr objectAtIndex:0];

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",[arr objectAtIndex:1]]];

//url like: "assets-library://asset/asset.MOV?id=78988A2B-203B-41B9-8EDA-F3029303DFBF&ext=MOV"

NSString * surl = [url absoluteString];
NSString * ext = [surl substringFromIndex:[surl rangeOfString:@"ext="].location + 4];

NSTimeInterval ti = [[NSDate date]timeIntervalSinceReferenceDate];
NSString *fname = [NSString stringWithFormat: @"%f.%@",ti,ext];

NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"SAVED_PHOTOS"];
// New Folder is your folder name
NSError *error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath])
    [[NSFileManager defaultManager] createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:&error];

NSString *tmpfile = [stringPath stringByAppendingPathComponent:fname];

ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset){
    ALAssetRepresentation * rep = [myasset defaultRepresentation];
    NSLog(@"video url: %@",rep.url);
    NSUInteger size = [rep size];

    NSLog(@"file size: %@",[NSString stringWithFormat:@"%llu",(unsigned long long)rep.size]);
    if (!appDelegate.arrFileSize) {
        appDelegate.arrFileSize = [[NSMutableArray alloc] init];
    }
    [appDelegate.arrFileSize replaceObjectAtIndex:[index integerValue] withObject:[NSString stringWithFormat:@"%llu",(unsigned long long)rep.size]];
    [appDelegate.accessToken setObject:appDelegate.arrFileSize forKey:@"FileSize"];
    [appDelegate.accessToken synchronize];
    NSLog(@"video fileSize: %@",[self convertbyteToKB_MB:(unsigned long long)rep.size]);
    unsigned long long freeSpaceSize = [self getFreeDiskspace];
    NSLog(@"freeSpaceSize: %llu",freeSpaceSize);

    if (freeSpaceSize<rep.size && rep.size<1073741824) {
        NSString *alertMsg;
        if (IS_IPHONE) {
            alertMsg = [NSString stringWithFormat:@"App requires %@ free storage space to upload this video. To proceed with this upload, please go to your iPhone's Settings and clear some space.",[self convertbyteToKB_MB:(unsigned long long)rep.size]];
        }
        else{
            alertMsg = [NSString stringWithFormat:@"App requires %@ free storage space to upload this video. To proceed with this upload, please go to your iPad's Settings and clear some space.",[self convertbyteToKB_MB:(unsigned long long)rep.size]];
        }
        dispatch_async(dispatch_get_main_queue(), ^{

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:alertMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.waitToUploadLbl.hidden = TRUE;
            });
        });

    }
    else{
        if (rep.size>=1073741824) {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.waitToUploadLbl.hidden = TRUE;
            });
        }
        else{
            convertingTotal++;
            dispatch_async(dispatch_get_main_queue(), ^{
                self.waitToUploadLbl.hidden = FALSE;
            });
            const int bufferSize = 8*1024*1024;
            FILE* f = fopen([tmpfile cStringUsingEncoding:1], "wb+");
            if (f == NULL) {
                return;
            }

            Byte * buffer = (Byte*)malloc(bufferSize);
            unsigned long long read = 0, offset = 0, written = 0;
            NSError* err;
            if (size != 0) {

                do {
                    read = (unsigned long long)[rep getBytes:buffer
                                                  fromOffset:offset
                                                      length:bufferSize
                                                       error:&err];
                    written = (unsigned long long)fwrite(buffer, sizeof(char), read, f);
                    offset += read;
                } while (read != 0);
                blockedNo++;
            }
            fclose(f);
            NSLog(@"file saved to temp");
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"total: %d blockedNo: %d",convertingTotal,blockedNo);
                self.waitToUploadLbl.hidden = TRUE;
           });
        }
    }

};

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

};

if(url)
{
    ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
    [assetslibrary assetForURL:url
                   resultBlock:resultblock
                  failureBlock:failureblock];
}
self.activityIndicator.hidden = TRUE;
@try {
    [appDelegate.uploadArray1 replaceObjectAtIndex:[index integerValue] withObject:tmpfile];
    [appDelegate.accessToken setObject:appDelegate.uploadArray1 forKey:@"UploadArray"];
    [appDelegate.accessToken synchronize];
    NSLog(@"temporary path: %@",tmpfile);
    [self performSelector:@selector(uploadphotoToServer:) withObject:index afterDelay:1];
}
@catch (NSException *exception) {
    NSLog(@"Error: %@",exception);
}
@finally {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (convertingTotal==blockedNo) {
            self.waitToUploadLbl.hidden = TRUE;
        }

    });
}
return tmpfile;
}

最佳答案

i hope this will help you

NSString *str_url=[arrURL objectAtIndex:indexPath.row];//put your index

                    ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];

                    NSURL* aURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@",str_url]];

                    [assetLibrary assetForURL:aURL resultBlock:^(ALAsset *asset) {

                        ALAssetRepresentation *rep = [asset defaultRepresentation];
                        Byte *buffer = (Byte*)malloc(rep.size);
                        NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:rep.size error:nil];
                        NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];

                        cell.imageCell.image=[UIImage imageWithData:data];


                    } failureBlock:^(NSError *error)
                     {
                         NSLog(@"Error: %@",[error localizedDescription]);
                     }];

关于ios - 如何从 iOS/iPhone 中的 Assets 库获取照片/视频源路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24406287/

相关文章:

ios - 报告 ALAssetRepresentation 元数据方法崩溃

ios - 无法在 Mac 上构建和运行 react-native 项目

ios - Objective-C:如何获取 UIScrollView 的缩放内容

ios - 从 ALAsset 库的路径获取 URLs 值

ios - 我们如何获取在 iphone/ipad 中创建的自定义文件夹的路径/url?

iOS : How to get image with specific size from AssetsLibrary

ios - 可选类型 'UIImage?' 的值未展开

ios - 在 iOS Playground 上使用 AVFoundation 的 Recorder,但 recorder.record() 总是返回 false

swift - ALAsset 已弃用 - 使用 Photos Framework 中的 PHAsset