2017년 1월 12일 목요일

비디오파일 duration 가져오기

- (NSString *)getVideoFileDuration:(NSString *)fileName {
    NSString *videoFilePath = [[self localVideoStorageDir] stringByAppendingPathComponent:fileName];
    NSURL *url = [NSURL fileURLWithPath:videoFilePath];
    AVURLAsset *sourceAsset = [AVURLAsset URLAssetWithURL:url options:nil];
    CMTime duration = sourceAsset.duration;
    NSInteger seconds = (int)CMTimeGetSeconds(duration);
    
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:seconds];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
    if (seconds >= 360) {
        [dateFormatter setDateFormat:@"HH:mm:ss"];
    } else{
        [dateFormatter setDateFormat:@"mm:ss"];
    }
    NSString* result = [dateFormatter stringFromDate:date];
    return result;

}

이미지 파일의 정보 가져오기

- (IBAction)touchedImageInfo:(id)sender {
    
    NSData *imagedata = [NSData dataWithContentsOfFile:_fileUrl];
    CGImageSourceRef source = CGImageSourceCreateWithData((CFMutableDataRef)imagedata, NULL);
    CFDictionaryRef dictRef = CGImageSourceCopyPropertiesAtIndex(source,0,NULL);
    NSDictionary* metadata = (__bridge NSDictionary *)dictRef;
    
    //NSLog(@"%@", metadata);
    CGFloat width = [metadata[@"PixelWidth"] floatValue];
    CGFloat height = [metadata[@"PixelHeight"] floatValue];
    
    NSMutableString *message = [[NSMutableString alloc] init];
    [message appendFormat:@"\n종류 : %@\n", [_fileUrl pathExtension]];
    [message appendFormat:@"크기 : %.01f KB\n", (float)imagedata.length/1024.f];
    [message appendFormat:@"해상도 : %d x %d\n", (int)width, (int)height];
    
    UIAlertController * alert = [UIAlertController
                                 alertControllerWithTitle:@"파일 정보"
                                 message:message
                                 preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* yesButton = [UIAlertAction
                                actionWithTitle:@"확인"
                                style:UIAlertActionStyleDefault
                                handler:^(UIAlertAction * action) {
                                }];
    [alert addAction:yesButton];
    [[Util topViewController] presentViewController:alert animated:YES completion:^{
        CFRelease(source);
        CFRelease(dictRef);
    }];

}

겔러리에 이미지/비디오 저장 하기 over iOS 8

#import <Photos/Photos.h>


- (IBAction)touchedImageSave:(id)sender {
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        PHAssetChangeRequest *changeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:_imageView.image];
        changeRequest.creationDate          = [NSDate date];
    } completionHandler:^(BOOL success, NSError *error) {
        if (success) {
            [[Util sharedInstance] showToastMessage:@"저장되었습니다."];
        }
        else {
            [[Util sharedInstance] showToastMessage:[NSString stringWithFormat:@"저장에 실패했습니다. (%@)", error.localizedDescription]];
        }
    }];

}



- (IBAction)touchedVideoSave:(id)sender {
    
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^
     {
         NSURL *url = [NSURL URLWithString:_fileUrl];
         [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:url];
     }
                                      completionHandler:^(BOOL success, NSError *error)
     {
         if (success) {
             [[Util sharedInstance] showToastMessage:@"저장되었습니다."];
         }
         else {
             [[Util sharedInstance] showToastMessage:[NSString stringWithFormat:@"저장에 실패했습니다. (%@)", error.localizedDescription]];
         }
     }];
}

2017년 1월 8일 일요일

겔러리에서 모든 이미지 불러오기

-(void)getAllPhotos
{
    [[Util sharedInstance] showLoadingView];
    
    NSMutableArray *photos = [[NSMutableArray alloc] init];
    PHFetchOptions *allPhotosOptions = [[PHFetchOptions alloc] init];
    allPhotosOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
    PHFetchResult *allPhotos = [PHAsset fetchAssetsWithOptions:allPhotosOptions];
    PHFetchResult *fetchResult = @[allPhotos][0];
    
    for (int x = 0; x < fetchResult.count; x ++) {
        
        PHAsset *asset = fetchResult[x];
        photos[x] = asset;
    }
    
    self.assets = photos;
    
    [[Util sharedInstance] hideLoadingView];
    [_collectionView reloadData];

}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.selectedAssets = [[NSMutableArray alloc] init];
    self.assets = [[NSMutableArray alloc] init];
    
    self.manager = [PHImageManager defaultManager];
    self.options = [[PHImageRequestOptions alloc] init];
    _options.resizeMode = PHImageRequestOptionsResizeModeFast;
    _options.deliveryMode = PHImageRequestOptionsDeliveryModeFastFormat;
    
    [self requestAuthorizationWithRedirectionToSettings];
    
    //[self performSelector:@selector(getAllPhotos) withObject:nil];

}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    BoardPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"BoardPhotoCell" forIndexPath:indexPath];
    
    cell.checkIndicator.hidden = NO;
    PHAsset *asset = [_assets objectAtIndex:indexPath.item];
    [_manager requestImageForAsset:asset
                       targetSize:CGSizeMake(1024.f,1024.f)
                      contentMode:PHImageContentModeDefault
                          options:_options
                    resultHandler:^void(UIImage *image, NSDictionary *info) {
                        cell.photo.image = image;
                    }];
    
    //update checkbox
    NSUInteger foundIndex = [_selectedAssets indexOfObject:asset];
    if (foundIndex != NSNotFound) {
        [cell setCheck:YES];
    } else {
        [cell setCheck:NO];
    }
    
    return cell;

}

갤러리 권한 요청

- (void)requestAuthorizationWithRedirectionToSettings {
    dispatch_async(dispatch_get_main_queue(), ^{
        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
        if (status == PHAuthorizationStatusAuthorized)
        {
            //We have permission. Do whatever is needed
        }
        else
        {
            //No permission. Trying to normally request it
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                if (status != PHAuthorizationStatusAuthorized)
                {
                    //User don't give us permission. Showing alert with redirection to settings
                    //Getting description string from info.plist file
                    NSString *accessDescription = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSPhotoLibraryUsageDescription"];
                    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:accessDescription message:@"To give permissions tap on 'Change Settings' button" preferredStyle:UIAlertControllerStyleAlert];

                    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
                    [alertController addAction:cancelAction];

                    UIAlertAction *settingsAction = [UIAlertAction actionWithTitle:@"Change Settings" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                    }];
                    [alertController addAction:settingsAction];

                    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
                }
            }];
        }
    });
}

출처 : http://stackoverflow.com/questions/13572220/ask-permission-to-access-camera-roll