Adding multiple assets to collection with Photo Framework - Objective-C - ios

I have the following code:
-(void) saveFromLocationsArray: (NSArray*) locations{
[self.photoLib performChanges:^{
PHAssetChangeRequest *creationRequest;
NSMutableArray *changesArray = [[NSMutableArray alloc] init];
for(int i=0; i<locations.count; i++){
creationRequest = [PHAssetChangeRequest creationRequestForAssetFromImageAtFileURL:locations[i]];
[changesArray addObject:[creationRequest placeholderForCreatedAsset]];
}
PHAssetCollectionChangeRequest *collectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:self.objcAppAlbum];
[collectionChangeRequest addAssets:changesArray];
} completionHandler:^(BOOL success, NSError *error) {
if(!success){
NSLog(#"an error has occured while trying to save pic to library: %#", error);
}
else{
NSLog(#"image was added to album ObjcApp");
}
}];
In a nutshell: I have an array of locations (URLS) of images I've just downloaded, and I'm trying to add them all to the iPhone's photo library. i managed to do so for one image (in a different method) but here it crashes on [collectionChangeRequest addAssets:changesArray], my guess is that the argument fo addAssest is invalid... but i can't figure out why.
this is the working code for one image only:
-(void) saveFromLocation: (NSURL*) location{
[self.photoLib performChanges:^{
PHAssetChangeRequest *creationRequest = [PHAssetChangeRequest creationRequestForAssetFromImageAtFileURL:location];
PHAssetCollectionChangeRequest *collectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:self.objcAppAlbum];
NSArray *arr = [NSArray arrayWithObjects:[creationRequest placeholderForCreatedAsset], nil];
[collectionChangeRequest addAssets:arr];
} completionHandler:^(BOOL success, NSError *error) {
if(!success){
NSLog(#"an error has occured while trying to save pic to library: %#", error);
}
else{
NSLog(#"image was added to album ObjcApp");
}
}];
}
error: 2019-03-05 14:26:26.062368 ObjcProject[1026:371314]
-[__NSCFString path]: unrecognized selector sent to instance 0x1740fa880 2019-03-05 14:26:26.063343 ObjcProject[1026:371314] *
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[__NSCFString path]:
unrecognized selector sent to instance 0x1740fa880'
* First throw call stack: (0x186d3d1b8 0x18577455c 0x186d44268 0x186d41270 0x186c3a80c 0x19276338c 0x192700ee8 0x19275e8c4
0x19275edfc 0x1914ae4b8 0x191d49c4c 0x19275e510 0x192738be4
0x1914a0ddc 0x1001dd258 0x1001dd218 0x1001eaaec 0x1001e0ce0
0x1001eb088 0x1001ece2c 0x1001ecb78 0x185dcf2a0 0x185dced8c)
libc++abi.dylib: terminating with uncaught exception of type
NSException

Related

how to use loadItemForTypeIdentifier to load an image

I have the following function which loads an image using the new PHPickerViewController:
- (void) picker:(PHPickerViewController *)picker didFinishPicking:(NSArray<PHPickerResult *> *)results
{
PHPickerResult *result = [results firstObject];
if (result)
{
[result.itemProvider loadObjectOfClass:[UIImage class] completionHandler:^(__kindof id<NSItemProviderReading> _Nullable object, NSError * _Nullable error)
{
dispatch_async(dispatch_get_main_queue(),
^{
if (!error)
{
[self pickerControllerDidFinishPickingWithImage:(UIImage *)object];
}
else
{
[self pickerControllerDidFinishWithError];
}
});
}];
}
}
I want to avoid using loadObjectOfClass because I don't want the image to load asynchronously. So I opted to use loadItemForTypeIdentifier instead and did the following:
[result.itemProvider loadItemForTypeIdentifier:#"public.image" options:nil completionHandler:^(__kindof id<NSItemProviderReading> _Nullable object, NSError * _Nullable error)
{
dispatch_async(dispatch_get_main_queue(),
^{
if (!error)
{
[self pickerControllerDidFinishPickingWithImage:(UIImage *)object];
}
else
{
[self pickerControllerDidFinishWithError];
}
});
}];
However, when I run this code I am getting:
ncaught exception 'NSInvalidArgumentException', reason: '-[NSURL
imageOrientation]: unrecognized selector sent to instance
0x600001ce5920' terminating with uncaught exception of type
NSException
I am not that great with blocks and this is my first time using a UTI so I'm wondering, what am I doing wrong here? Is it even possible to accomplish what I'm trying to accomplish, i.e. pull a UIImage out using loadItemForTypeIdentifier? Am I getting the syntax wrong?

Exception in saving a lot of files with PHPhotoLibrary API

My application has function to downloads many photo and video files in tmp folder and save them in camera roll with PHPhotoLibrary API.
The problem is that sometimes (the probability is around 10%) exception happens in the saving process.
The error message in console is,
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'This method can only be
called from inside of -[PHPhotoLibrary performChanges:completionHandler:] or -[PHPhotoLibrary
performChangesAndWait:error:]'
My code is like below:
- (void)saveVideoFileInCameraRoll:(NSString *)videoFilePath
{
NSURL *videoFileUrl = [NSURL fileURLWithPath:videoFilePath];
photoLibrarySaveImageCompletion completion = ^(BOOL success, NSError *error) {
NSLog(#"success=%#, error=%#", (success ? #"YES" : #"NO"), error);
};
NSLog(#"videoFileUrl=%#", videoFileUrl);
[self saveVideoFile:videoFileUrl completion:completion];
}
- (void)saveVideoFile:(NSURL *)fileURL completion:(photoLibrarySaveImageCompletion)completion
{
NSLog(#"fileURL=%#", fileURL);
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
NSLog(#"fileURL=%#", fileURL);
// Exception happens on this line as [SIGABRT]
PHAssetChangeRequest *assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:fileURL];
if (_assetCollection) {
PHAssetCollectionChangeRequest *assetCollectionChangeRequest =
[PHAssetCollectionChangeRequest changeRequestForAssetCollection:self.assetCollection];
[assetCollectionChangeRequest addAssets:#[ [assetChangeRequest placeholderForCreatedAsset] ]];
}
else {
NSLog(#"### assetCollection is nil ###");
}
}
completionHandler:^(BOOL success, NSError *_Nullable error) {
NSLog(#"success=%#, error=%#", (success ? #"YES" : #"NO"), error);
completion(success, error);
}];
}
I checked similar case:
Save image to photo library using photo framework
The case crashes every time, but my code rarely crashes.
And unlike the case I'm calling
[PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:]
in 'performChanges' block
Also I confirmed the fileURL of video file in tmp folder by NSLog and it's OK outside and inside of 'performChanges' block.
fileURL=file:///private/var/mobile/Containers/Data/Application/C87F0F75-E128-4E9F-AE07-6B914939AC5D/tmp/video3.mp4
I would appreciate it if you would let me know the reason or resolution of this issue.

Retrieve the names of photos albums (ALAssetsGroup) in Photos.app crash

I'm trying to get all the albums names. here is what I do.
The method [group valueForKey:ALAssetsGroupPropertyName] crashes
ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
[assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos | ALAssetsGroupAlbum
usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if (nil != group)
{
NSLog(#"name %#",[group valueForKey:ALAssetsGroupPropertyName]);
}
*stop = NO;
} failureBlock:^(NSError *error) {
NSLog(#"error: %#", error);
}];
I really don't know why it crashes, if someone knows, I'll really appreciate some help !
Here is the crash log :
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<ALAssetsGroup 0x17801ff90> valueForUndefinedKey:]: this class is not key value coding-compliant for the key ALAssetsGroupPropertyName.`
You are calling the wrong method. Change this:
NSLog(#"name %#",[group valueForKey:ALAssetsGroupPropertyName]);
to:
NSLog(#"name %#",[group valueForProperty:ALAssetsGroupPropertyName]);

Saving a video to Core Data

I am trying to save a video to core data but it is not working. When I added a break point it stopped on NSData *videoData = [NSData dataWithContentsOfUrl:self.videoURL]; What should I do to solve this.
Here is the code I am using to save the video:
- (void) saveVideo {
NSManagedObjectContext *context = [self managedObjectContext];
TimeTravelFeed *timeTravelFeed = [NSEntityDescription insertNewObjectForEntityForName:#"TimeTravelFeed" inManagedObjectContext:context];
NSData *videoData = [NSData dataWithContentsOfUrl:self.videoURL];
[timeTravelFeed setValue:videoData forKey:#"videoData"];
NSError *error = nil;
if (![self.managedObjectContext save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
Here is the error:
+[NSData dataWithContentsOfUrl:]: unrecognized selector sent to class 0x3b2947f4
2013-12-08 12:31:57.078 App Name[203:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[NSData dataWithContentsOfUrl:]: unrecognized selector sent to class 0x3b2947f4'
Your error is due to the fact that dataWithContentsOfUrl: is not a method of NSData, dataWithContentsOfURL: (capital R and L) is.
More importantly though is the fact that you shouldn't be saving the entire video into Core Data, you should save the video file to disk and store the file URL to Core Data instead.

xcode running well on simulator but when deploy to ios 6 encounter error

2012-10-08 14:48:14.579 sageby[2716:907] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[SBJsonParser errorTrace]: unrecognized selector sent to instance 0x1fda4660'
* First throw call stack:
(0x352412a3 0x34a1397f 0x35244e07 0x35243531 0x3519af68 0x12932f 0x1293a7 0x12cda3 0x12c9b1 0x12c753 0x12aac7 0x12e567 0x12eac3 0x3a26bef5 0x3a1ab9f1 0x3a1ab90d 0x384ba5df 0x384b9ccb 0x384e2133 0x3518774d 0x384e2593 0x3844615d 0x35216683 0x35215ee9 0x35214cb7 0x35187ebd 0x35187d49 0x35ef02eb 0x37dcd301 0xaaaf1 0x39e0cb20)
libc++abi.dylib: terminate called throwing an exception
(lldb)
//MBProgressHUD
MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.labelText=#"Accessing account..";
hud.labelFont=[UIFont fontWithName:#"Arial Rounded MT Bold" size:14];
//URL GETTING
NSString *phpfile=[[NSString alloc]initWithFormat:#"http://dev.xxxx.com/pxxx/Module_MyPxxx/json_xxxx_xxx_info.php"];
NSString *param_str=[[NSString alloc]initWithFormat:#"email=%#", mydelegate.overall_email];
NSString *receivedDataAsString=[mydelegate phpConnection:param_str :phpfile];
SBJsonParser *parser=[[SBJsonParser alloc]init];
NSError *error=nil;
self.dic_user_info=[[parser objectWithString:receivedDataAsString error:&error]objectAtIndex:0];
if(error)
{
NSLog(#"JSON Parser error! Reason: %#", error.localizedDescription);
}
//URL GETTING
phpfile=[[NSString alloc]initWithFormat:#"http://dev.xxx.com/pxxx/Module_MyPxxx/json_get_xxx_xxx_pxxx.php"];
param_str=[[NSString alloc]initWithFormat:#"email=%#", mydelegate.overall_email];
receivedDataAsString=[mydelegate phpConnection:param_str :phpfile];
parser=[[SBJsonParser alloc]init];
error=nil;
self.array_polls=[parser objectWithString:receivedDataAsString error:&error];
if(error)
{
NSLog(#"JSON Parser error! Reason: %#", error.localizedDescription);
}
[self.tableView reloadData];
[MBProgressHUD hideHUDForView:self.view animated:YES];
hi i'm the developer of the application.
The problem is that running on Xcode 4.5 is correct but just running on iphone device it wont work..

Resources