PHAssetChangeRequest always returns zero when creating video assets
I am saving a newly created video file to local documents. Then I would like to copy it to the Photo Library using the Photos framework.
The problem is that even though the video is being checked out (and I can validate it there and to watch), the following create request always returns nil:
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
// NSString filePath points to the newly-created file in Documents directory
NSParameterAssert([[NSFileManager defaultManager] isReadableFileAtPath:filePath]);
// path looks fine
NSURL* url = [NSURL URLWithString:filePath];
PHAssetChangeRequest* createAssetRequest = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:url];
// got back nil from creationRequestForAssetFromVideoAtFileURL, so we will assert out here
NSParameterAssert(createAssetRequest);
}
completionHandler:^(BOOL success, NSError *error) {}];
+3
source to share
2 answers
Unsurprisingly, the url was the problem. url = [NSURL URLWithString:filePath]
does not point to a movie file. It's ok if I get url
in (for example) like this:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *documentsURL = [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSArray *contents = [fileManager contentsOfDirectoryAtURL:documentsURL
includingPropertiesForKeys:@[]
options:NSDirectoryEnumerationSkipsHiddenFiles
error:nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"lastPathComponent == 'movie.mov'"];
NSURL* url = nil;
for (NSURL *fileURL in [contents filteredArrayUsingPredicate:predicate]) {
url = fileURL;
}
0
source to share
You need to use NSURL* url = [NSURL fileURLWithPath:filePath];
. This is my demo code, work well for me:
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
NSURL *localFileUrl = [NSURL fileURLWithPath:localSavedPath];
PHAssetChangeRequest *assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:localFileUrl];
if (localAssetCollection != nil) {
PHAssetCollectionChangeRequest *assetCollectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:localAssetCollection];
[assetCollectionChangeRequest addAssets:@[[assetChangeRequest placeholderForCreatedAsset]]];
}
} completionHandler:^(BOOL success, NSError *error) {
}];
My demo also supports changing the asset collection.
0
source to share