本文介绍了iOS会听取用户是否拍照的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当iPhone应用程序在后台时,有没有办法收听文件系统更改?我想创建一个云托管应用程序,如果您添加新文件而不必先打开应用程序,则会自动将照片上传到云端。

Is there a way to listen to the file system change while an iPhone app is in the background? I want to create a cloud hosting app that will automatically upload your photos to the cloud if you add a new file without having to open the app first.

例如,如果用户拍摄新照片或拍摄屏幕截图或录制内容。我是否可以收到已将项目添加到文件系统的通知?

For example, if a user takes a new photo or takes a screenshot or a recording. Can I be notified that an item has been added to the filesystem?

推荐答案

您可以使用照片框架宣布iOS8发布。

You can do this with Photos Framework which is announced iOS8 release.

阅读有关更改观察者的文档

Apple样本

更改观察。使用共享的 PHPhotoLibrary 对象为您获取的资产和集合注册更改处理程序。只要其他应用或设备更改资产的内容或元数据或集合中的资产列表,照片就会告知您的应用。
PHChange
对象提供有关每次更改前后对象状态的信息,其语义使得更新集合视图或类似界面变得容易

Change observing. Use the shared PHPhotoLibrary object to register a change handler for the assets and collections you fetch. Photos tells your app whenever another app or device changes the content or metadata of an asset or the list of assets in a collection. PHChange objects provide information about object state before and after each change with semantics that make it easy to update a collection view or similar interface

您如果照片应用程序有任何更新,可以拍照,使用**照片框架

You can take photos if any update on photos app, by using **photos framework

首先你需要注册照片观察者

- (void)applicationWillTerminate:(UIApplication *)application {
    [[PHPhotoLibrary sharedPhotoLibrary] unregisterChangeObserver:self];
}



 - (void)applicationDidBecomeActive:(UIApplication *)application {
        [FBSDKAppEvents activateApp];
        [[UIApplication sharedApplication] endBackgroundTask:UIBackgroundTaskInvalid];
        [[PHPhotoLibrary sharedPhotoLibrary] unregisterChangeObserver:self];
        //    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
        //        //Background Thread
        //        isBackgroundOrForeground = YES;
        //        [self getGreenEvent];
        //        dispatch_async(dispatch_get_main_queue(), ^(void){
        //            //Run UI Updates
        //        });
        //    });

    }
- (void)applicationDidEnterBackground:(UIApplication *)application {
    NSLog(@"=== DID ENTER BACKGROUND ===");
    bgTask = [[UIApplication  sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
    }];

    if (bgTask == UIBackgroundTaskInvalid) {
        NSLog(@"This application does not support background mode");
    } else {
        //if application supports background mode, we'll see this log.
        NSLog(@"Application will continue to run in background");
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status == PHAuthorizationStatusAuthorized) {
                [PHPhotoLibrary.sharedPhotoLibrary registerChangeObserver:self];
            }
        }];
        [[PHPhotoLibrary sharedPhotoLibrary] registerChangeObserver:self];
        isBackgroundOrForeground = NO;
        NSString *oAuthToken = [[NSUserDefaults standardUserDefaults]stringForKey:KEY_ACCESS_TOKEN];
        if(oAuthToken.length!=0 || oAuthToken!=nil)
            [self getGreenEvent];
    }
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}



pragma mark - PHPhotoLibraryChangeObserver



pragma mark - PHPhotoLibraryChangeObserver

- (void)photoLibraryDidChange:(PHChange *)changeInstance {
    NSLog(@"content being changed");
    /*
     Change notifications may be made on a background queue. Re-dispatch to the
     main queue before acting on the change as we'll be updating the UI.
     */
    __block BOOL reloadRequired = NO;
    __block NSIndexSet *removedIndex;
    __block NSIndexSet *insertedIndexes;
    dispatch_async(dispatch_get_main_queue(), ^{
        // Loop through the section fetch results, replacing any fetch results that have been updated.
        NSMutableArray *updatedSectionFetchResults = [self.sectionFetchResults mutableCopy];
        //        __block BOOL reloadRequired = NO;
        [self.sectionFetchResults enumerateObjectsUsingBlock:^(PHFetchResult *collectionsFetchResult, NSUInteger index, BOOL *stop) {
            PHFetchResultChangeDetails *changeDetails = [changeInstance changeDetailsForFetchResult:collectionsFetchResult];
            removedIndex = changeDetails.removedIndexes;
            insertedIndexes = changeDetails.insertedIndexes;
            if (changeDetails != nil) {
                [updatedSectionFetchResults replaceObjectAtIndex:index withObject:[changeDetails fetchResultAfterChanges]];
                reloadRequired = YES;
                self.sectionFetchResults = updatedSectionFetchResults;
                if(insertedIndexes != nil){
                    [self backgroundUpload];
                }else{
                }

            }

        }];
        if (reloadRequired) {
            self.sectionFetchResults = updatedSectionFetchResults;

        }

    });

}
-(void)getAllPhotosFromCamera{
    PHFetchOptions *allPhotosOptions = [[PHFetchOptions alloc] init];
    allPhotosOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
    PHFetchResult *allPhotos = [PHAsset fetchAssetsWithOptions:allPhotosOptions];
    PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    PHFetchResult *topLevelUserCollections = [PHCollectionList fetchTopLevelUserCollectionsWithOptions:nil];
    // Store the PHFetchResult objects and localized titles for each section.
    self.sectionFetchResults = @[allPhotos, smartAlbums, topLevelUserCollections];
}
-(NSMutableArray *)getNumberOfPhotoFromCameraRoll:(NSArray *)array{
    PHFetchResult *fetchResult = array[1];
    int index = 0;
    unsigned long pictures = 0;
    for(int i = 0; i < fetchResult.count; i++){
        unsigned long temp = 0;
        temp = [PHAsset fetchAssetsInAssetCollection:fetchResult[i] options:nil].count;
        if(temp > pictures ){
            pictures = temp;
            index = i;
        }
    }
    PHCollection *collection = fetchResult[index];

    if (![collection isKindOfClass:[PHAssetCollection class]]) {
        // return;
    }
    // Configure the AAPLAssetGridViewController with the asset collection.
    PHAssetCollection *assetCollection = (PHAssetCollection *)collection;
    PHFetchResult *assetsFetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
    self. assetsFetchResults = assetsFetchResult;
    self. assetCollection = assetCollection;
    self.numberOfPhotoArray = [NSMutableArray array];
    for (int i = 0; i<[assetsFetchResult count]; i++) {
        PHAsset *asset = assetsFetchResult[i];
        [self.numberOfPhotoArray addObject:asset];
    }
    NSLog(@"%lu",(unsigned long)[self.numberOfPhotoArray count]);
    return self.numberOfPhotoArray;
}

其中bgTask是

UIBackgroundTaskIdentifier bgTask;

UIBackgroundTaskIdentifier bgTask;

@property (nonatomic, strong) NSArray *sectionFetchResults;
@property (nonatomic, strong) PHFetchResult *assetsFetchResults;
@property (nonatomic, strong) PHAssetCollection *assetCollection;
@property (nonatomic, strong) NSMutableArray *numberOfPhotoArray;

这篇关于iOS会听取用户是否拍照的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 03:55