#import "GengmeiFlutterPlugin.h" #import #import #import "Image/AlbumItem.h" #import "ResultManager.h" #import #import #import "MyPlayerViewController.h" #import "MyPreviewController.h" @interface GengmeiFlutterPlugin () //一定要声明这三个协议,缺一不可 //@property(nonatomic)FlutterResult result; @property(atomic)int needSize; @property(atomic)int nowSize; @property(atomic)int copySize; @property(nonatomic) long resultKey; @property(nonatomic)long nativeCameraKey; @property(strong,atomic)NSMutableDictionary*>*>* finalMap; @property(strong,atomic)NSMutableDictionary*>*>* finalMapTemp; @property(nonatomic,strong) UIImagePickerController *imagePicker; @property(nonatomic)Boolean quitPage; @property(atomic)Boolean finishScanImg; @property(atomic,strong)NSMutableDictionary*scanMap; @property(atomic,strong)NSMutableDictionary*takePhotoMap; @property(atomic,strong)NSMutableArray* channelList; @property(atomic)int channelSize; @property(atomic)int channelAllSize; @end @implementation GengmeiFlutterPlugin dispatch_queue_t concurrentQueue; FlutterEventSink _eventSink; NSMutableArray *assetCollectionList; UIViewController * viewController; dispatch_queue_t queue; NSObject* resign; FlutterEventSink _eventSink; NSString *cacheDirectory; + (void)registerWithRegistrar:(NSObject*)registrar { GengmeiFlutterPlugin* instance = [[GengmeiFlutterPlugin alloc] init]; // resign=registrar; FlutterMethodChannel* channel = [FlutterMethodChannel methodChannelWithName:@"gengmei_flutter_plugin" binaryMessenger:[registrar messenger]]; [registrar addMethodCallDelegate:instance channel:channel]; assetCollectionList = [NSMutableArray array]; viewController =[UIApplication sharedApplication].delegate.window.rootViewController; concurrentQueue = dispatch_queue_create("com.gengmei_flutter_plugin", DISPATCH_QUEUE_CONCURRENT); // concurrentQueue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0); queue = dispatch_queue_create("com.gengmei_flutter_plugin", DISPATCH_QUEUE_SERIAL); FlutterEventChannel* chargingChannel = [FlutterEventChannel eventChannelWithName:@"gengmei_flutter_plugin_event" binaryMessenger:[registrar messenger]]; [chargingChannel setStreamHandler:instance]; NSString *cacheDirectory1 = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject]; cacheDirectory = [NSString stringWithFormat:@"%@/GM", cacheDirectory1]; if (![[NSFileManager defaultManager] fileExistsAtPath:cacheDirectory]) { [[NSFileManager defaultManager] createDirectoryAtPath:cacheDirectory withIntermediateDirectories:YES attributes:nil error:nil]; } } - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result { self.resultKey++; [[ResultManager sharedSingleton] addResult:[NSNumber numberWithLong:self.resultKey] :result]; if ([@"scan_image_picker" isEqualToString:call.method]) { ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus]; NSString *mediaType = AVMediaTypeVideo; //读取媒体类型 AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType]; //读取设备授权状态 NSLog(@"STATE %d",authStatus); if(author ==AVAuthorizationStatusAuthorized){ NSLog(@"相机可用"); long temp=self.resultKey; [self scanPhone:temp]; } else if(author == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) { NSLog(@"没给权限!!!"); NSString *errorStr = @"应用相机权限受限,请在iPhone的“设置-隐私-相册”选项中,允许好享玩访问你的相册。"; [self popWindow:errorStr]; }else { NSLog(@"HERRRRRRRR"); [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) { if(status == PHAuthorizationStatusAuthorized) { dispatch_async(dispatch_get_main_queue(), ^{ // 用户点击 "OK" long temp=self.resultKey; [self scanPhone:temp]; }); } else { dispatch_async(dispatch_get_main_queue(), ^{ // 用户点击 不允许访问 NSString *errorStr = @"应用相机权限受限,请在iPhone的“设置-隐私-相册”选项中,允许好享玩访问你的相册。"; [self popWindow:errorStr]; NSLog(@"被拒绝 TODO!!"); }); } }]; } } else if([@"native_camera" isEqualToString:call.method]){ self.nativeCameraKey=self.resultKey; NSString *mediaType = AVMediaTypeVideo;//读取媒体类型 AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];//读取设备授 if(authStatus ==AVAuthorizationStatusAuthorized){ NSLog(@"相机可用"); [self nativeCamera]; } else if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){ NSString *errorStr = @"应用相机权限受限,请在iPhone的“设置-隐私-相机”选项中,允许好享玩访问你的相机。"; NSLog(@"相机不可用"); [self popWindow:errorStr]; }else { [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) { if(granted){ [self nativeCamera]; }else{ NSString *errorStr = @"应用相机权限受限,请在iPhone的“设置-隐私-相册”选项中,允许好享玩访问你的相册。"; [self popWindow:errorStr]; } }]; } }else if([@"quit_page" isEqualToString:call.method]){ self.quitPage=true; }else if([@"SAVE_STRING_SHARED" isEqualToString:call.method]){ long temp=self.resultKey; NSString *key=call.arguments[@"key"]; NSString * value=call.arguments[@"value"]; dispatch_async(queue, ^{ [[NSUserDefaults standardUserDefaults] setValue:value forKey:key]; dispatch_async(dispatch_get_main_queue(), ^{ [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:temp] :@YES]; }); }); }else if([@"SAVE_INT_SHARED" isEqualToString:call.method]){ long temp=self.resultKey; NSString *key=call.arguments[@"key"]; NSNumber* value=call.arguments[@"value"]; dispatch_async(queue, ^{ [[NSUserDefaults standardUserDefaults] setValue:value forKey:key]; dispatch_async(dispatch_get_main_queue(), ^{ [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:temp] :@YES]; }); }); }else if([@"SAVE_FLOAT_SHARED" isEqualToString:call.method]){ long temp=self.resultKey; NSString *key=call.arguments[@"key"]; NSNumber* value=call.arguments[@"value"]; dispatch_async(queue, ^{ [[NSUserDefaults standardUserDefaults] setObject:value forKey:key]; dispatch_async(dispatch_get_main_queue(), ^{ [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:temp] :@YES]; }); }); } else if([@"SAVE_BOOLEAN_SHARED" isEqualToString:call.method]){ long temp=self.resultKey; NSString *key=call.arguments[@"key"]; bool value=call.arguments[@"value"]; dispatch_async(queue, ^{ [[NSUserDefaults standardUserDefaults] setBool:value forKey:key]; dispatch_async(dispatch_get_main_queue(), ^{ [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:temp] :@YES]; }); }); }else if([@"SAVE_STRINGLIST_SHARED" isEqualToString:call.method]){ long temp=self.resultKey; NSString *key=call.arguments[@"key"]; NSArray * value=call.arguments[@"value"]; dispatch_async(queue, ^{ [[NSUserDefaults standardUserDefaults] setValue:value forKey:key]; dispatch_async(dispatch_get_main_queue(), ^{ [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:temp] :@YES]; }); }); }else if([@"GET_STRING_SHARED" isEqualToString:call.method]){ long temp=self.resultKey; NSString *key=call.arguments[@"key"]; NSString * value=call.arguments[@"value"]; dispatch_async(queue, ^{ __block NSString* result=[[NSUserDefaults standardUserDefaults] objectForKey:key]; dispatch_async(dispatch_get_main_queue(), ^{ if(result==nil) result=value; [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:temp] :result]; }); }); }else if([@"GET_FLOAT_SHARED" isEqualToString:call.method]){ long temp=self.resultKey; NSString *key=call.arguments[@"key"]; NSNumber* value=call.arguments[@"value"]; dispatch_async(queue, ^{ __block NSNumber* result=[[NSUserDefaults standardUserDefaults] objectForKey:key]; dispatch_async(dispatch_get_main_queue(), ^{ if(result==nil) result=value; [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:temp] :result]; }); }); }else if([@"GET_INT_SHARED" isEqualToString:call.method]){ long temp=self.resultKey; NSString *key=call.arguments[@"key"]; NSNumber* value=call.arguments[@"value"]; dispatch_async(queue, ^{ __block NSNumber* result=[[NSUserDefaults standardUserDefaults] objectForKey:key]; dispatch_async(dispatch_get_main_queue(), ^{ if(result==nil) result=value; [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:temp] :result]; }); }); }else if([@"GET_BOOLEAN_SHARED" isEqualToString:call.method]){ long temp=self.resultKey; NSString *key=call.arguments[@"key"]; NSNumber * value=call.arguments[@"value"]; dispatch_async(queue, ^{ __block NSNumber* result=[[NSUserDefaults standardUserDefaults] objectForKey:key]; dispatch_async(dispatch_get_main_queue(), ^{ if(result==nil) result=value; [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:temp] :result]; }); }); }else if([@"GET_STRINGLIST_SHARED" isEqualToString:call.method]){ long temp=self.resultKey; NSString *key=call.arguments[@"key"]; NSArray * value=call.arguments[@"value"]; dispatch_async(queue, ^{ __block NSArray* result=[[NSUserDefaults standardUserDefaults] objectForKey:key]; dispatch_async(dispatch_get_main_queue(), ^{ if(result==nil) result=value; [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:temp] :result]; }); }); }else if([@"CLEAR_SHARE" isEqualToString:call.method]){ long temp=self.resultKey; dispatch_async(queue, ^{ [self clearAllUserDefaultsData]; dispatch_async(dispatch_get_main_queue(), ^{ [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:temp] :@YES]; }); }); }else if([@"IOS_IMAGE_BY_PATH" isEqualToString:call.method]){ NSArray *path=call.arguments; long resultTemp=self.resultKey; if(path!=nil){ dispatch_async(concurrentQueue, ^{ [self.channelList removeAllObjects]; if(path.count==0){ dispatch_async(dispatch_get_main_queue(), ^{ [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:resultTemp] :self.channelList]; }); return ; } self.channelSize=0; self.channelAllSize=path.count; PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init]; options.version = PHImageRequestOptionsVersionCurrent; options.networkAccessAllowed = true; options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic; PHImageRequestOptions *imageRequestOption = [[PHImageRequestOptions alloc] init]; imageRequestOption.synchronous =NO; imageRequestOption.networkAccessAllowed = YES; imageRequestOption.deliveryMode=PHImageRequestOptionsDeliveryModeHighQualityFormat; imageRequestOption.resizeMode=PHImageRequestOptionsResizeModeFast; imageRequestOption.version=PHImageRequestOptionsVersionUnadjusted; NSString *tempPath = NSTemporaryDirectory(); NSFileManager *fileManager = [NSFileManager defaultManager]; for (int i=0; ilimit){ // tempScareSize=limit/max; // } // // CGSize temp=CGSizeMake(picWidth*tempScareSize, picHeight*tempScareSize); dispatch_async(concurrentQueue, ^{ NSString* tempTake1= [tempPath stringByAppendingPathComponent:[path[i] lastPathComponent]]; [[PHImageManager defaultManager] requestImageDataForAsset:assets options:imageRequestOption resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) { // [[PHImageManager defaultManager] requestImageForAsset:assets targetSize:temp contentMode:PHImageContentModeDefault options:imageRequestOption resultHandler:^(UIImage * _Nullable res, NSDictionary * _Nullable info) { dispatch_async(concurrentQueue, ^{ @autoreleasepool{ UIImage * res=[UIImage imageWithData:imageData]; NSData *data = UIImageJPEGRepresentation(res, 0.8) ; [data writeToFile:tempTake1 atomically:YES]; res=nil; data=nil; } NSMutableDictionary *dict=[[NSMutableDictionary alloc] init]; [dict setObject:path[i] forKey:@"path"]; [dict setObject:tempTake1 forKey:@"realImagePath"]; @synchronized (self) { self.channelSize++; [self.channelList addObject:dict]; } if(self.channelSize==self.channelAllSize){ dispatch_async(dispatch_get_main_queue(), ^{ [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:resultTemp] :self.channelList]; }); } }); }]; }); } } }else if ([[self.takePhotoMap allKeys] containsObject:path[i]]){ NSMutableDictionary *dict=[[NSMutableDictionary alloc] init]; [dict setObject:path[i] forKey:@"path"]; [dict setObject:self.takePhotoMap[path[i]] forKey:@"realImagePath"]; @synchronized (self) { self.channelSize++; [self.channelList addObject:dict]; } if(self.channelSize==self.channelAllSize){ dispatch_async(dispatch_get_main_queue(), ^{ [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:resultTemp] :self.channelList]; }); } }else{ [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:resultTemp] :nil]; } } }); }else{ [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:resultTemp] :nil]; } }else if([@"PREVIEW_IMAGE" isEqualToString:call.method]){ long resultTemp=self.resultKey; NSString*path=call.arguments; PHImageRequestOptions *imageRequestOption = [[PHImageRequestOptions alloc] init]; imageRequestOption.synchronous =NO; imageRequestOption.networkAccessAllowed = YES; imageRequestOption.deliveryMode=PHImageRequestOptionsDeliveryModeHighQualityFormat; imageRequestOption.resizeMode=PHImageRequestOptionsResizeModeFast; imageRequestOption.version=PHImageRequestOptionsVersionUnadjusted; NSString *tempPath = NSTemporaryDirectory(); NSFileManager *fileManager = [NSFileManager defaultManager]; if([[self.scanMap allKeys] containsObject:path]){ NSString* name=[path lastPathComponent]; NSString* tempTake= [tempPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@",name,@"_preview"]]; PHAsset * assets=self.scanMap[path]; MyPreviewController* video=[[MyPreviewController alloc] init]; [viewController presentViewController:video animated:YES completion:nil]; [video setImagePre:assets]; [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:resultTemp] :@YES]; }else if ([[self.takePhotoMap allKeys] containsObject:path]){ MyPreviewController* video=[[MyPreviewController alloc] init]; [viewController presentViewController:video animated:YES completion:nil]; [video setImagePrePath:self.takePhotoMap[path]]; [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:resultTemp] :@YES]; // NSMutableDictionary *dict=[[NSMutableDictionary alloc] init]; // [dict setObject:path forKey:@"path"]; // [dict setObject:self.takePhotoMap[path] forKey:@"realImagePath"]; // [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:resultTemp] :dict]; }else{ [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:resultTemp] :nil]; } }else if([@"scare_image" isEqualToString:call.method] ){ long resultTemp=self.resultKey; NSMutableDictionary * dict =call.arguments; int size=dict[@"size"]; PHImageRequestOptions *imageRequestOption = [[PHImageRequestOptions alloc] init]; imageRequestOption.synchronous =NO; imageRequestOption.networkAccessAllowed = YES; imageRequestOption.deliveryMode=PHImageRequestOptionsDeliveryModeHighQualityFormat; imageRequestOption.resizeMode=PHImageRequestOptionsResizeModeFast; imageRequestOption.version=PHImageRequestOptionsVersionUnadjusted; NSString *tempPath = NSTemporaryDirectory(); NSFileManager *fileManager = [NSFileManager defaultManager]; NSString* path=dict[@"path"]; if(path!=nil){ if([[self.scanMap allKeys] containsObject:path]){ NSString* name=[path lastPathComponent]; NSString* tempTake= [tempPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@",name,@"_preview"]]; PHAsset * assets=self.scanMap[path]; if([fileManager fileExistsAtPath:tempTake]){ [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:resultTemp] :tempTake]; }else{ dispatch_async(queue, ^{ CFAbsoluteTime start=CFAbsoluteTimeGetCurrent(); int picWidth=[assets pixelWidth]; int picHeight=[assets pixelHeight]; float tempScareSize=1; float limit=size+0.0; float max=MAX(picWidth, picHeight); if(max>limit){ tempScareSize=limit/max; } CGSize temp=CGSizeMake(picWidth*tempScareSize, picHeight*tempScareSize); __block bool isResult=false; [[PHImageManager defaultManager] requestImageForAsset:assets targetSize:temp contentMode:PHImageContentModeDefault options:imageRequestOption resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) { if(isResult){ return ; } isResult=true; @autoreleasepool{ NSData *data = UIImageJPEGRepresentation(result, 1) ; [data writeToFile:tempTake atomically:YES]; // result=nil; // data=nil; } NSLog(@"压缩预览图片耗时:%f ms Temp路径%@",(CFAbsoluteTimeGetCurrent()-start)*1000,tempTake); [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:resultTemp] :tempTake]; }]; }); } }else if ([[self.takePhotoMap allKeys] containsObject:path]){ [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:resultTemp] :self.takePhotoMap[path]]; } } }else if([@"play_album_video" isEqualToString:call.method] ){ long resultTemp=self.resultKey; NSString * path=call.arguments; if([[self.scanMap allKeys] containsObject:path]){ PHAsset * assets=self.scanMap[path]; MyPlayerViewController* video=[[MyPlayerViewController alloc] init]; [viewController presentViewController:video animated:YES completion:nil]; // video.player= [[AVPlayeralloc]initWithURL:url]; [video playMovie:assets]; [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:resultTemp] :@YES]; // PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init]; // options.version = PHImageRequestOptionsVersionCurrent; // options.networkAccessAllowed = true; // options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic; // [[PHImageManager defaultManager]requestAVAssetForVideo:assets options:options resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) { // AVURLAsset *urlAsset = (AVURLAsset *)asset; // AVPlayerViewController* video=[[AVPlayerViewController alloc] init]; // [viewController presentViewController:video animated:YES completion:nil]; // [video playMovie:urlAsset.URL]; // [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:resultTemp] :@YES]; // }]; } }else{ result(FlutterMethodNotImplemented); } } - (void)showToast:(NSString *)text inView:(UIView *)superView { if (!superView) { return; } CGSize labelSize = [text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20.f]}]; UILabel *label = [[UILabel alloc] init]; label.font = [UIFont systemFontOfSize:18.f]; label.text = text; label.textAlignment = NSTextAlignmentCenter; label.layer.cornerRadius = labelSize.height/4; label.layer.masksToBounds = YES; label.backgroundColor = [UIColor colorWithRed:38/255.f green:187/255.f blue:251/255.f alpha:1.f]; label.textColor = [UIColor whiteColor]; label.frame = CGRectMake((superView.bounds.size.width - labelSize.width)/2, 0, labelSize.width, labelSize.height); [superView addSubview:label]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [label removeFromSuperview]; }); } - (void)clearAllUserDefaultsData { NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; NSDictionary *dic = [userDefaults dictionaryRepresentation]; for (id key in dic) { [userDefaults removeObjectForKey:key]; } [userDefaults synchronize]; } -(void)nativeCamera{ self.imagePicker = [[UIImagePickerController alloc] init]; // 设置代理 self.imagePicker.delegate = self; // 是否显示裁剪框编辑(默认为NO),等于YES的时候,照片拍摄完成可以进行裁剪 self.imagePicker.allowsEditing = NO; // 设置照片来源为相机 self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera; // 设置进入相机时使用前置或后置摄像头 self.imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceRear; self.imagePicker.modalPresentationStyle=UIModalPresentationFullScreen; // 展示选取照片控制器 [viewController presentViewController:self.imagePicker animated:YES completion:nil]; } - (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{ NSLog(@"imageSavedToPhotosAlbum"); NSString *message = @""; if (!error) { dispatch_async(queue, ^{ NSString *tempPath = NSTemporaryDirectory(); NSString* tempTake= [tempPath stringByAppendingPathComponent:[NSString stringWithFormat:@"image_picker_%@", [[NSProcessInfo processInfo] globallyUniqueString]]]; NSData *takeData= UIImageJPEGRepresentation(image,0.8); [takeData writeToFile:tempTake atomically:YES]; CGFloat fixelW = CGImageGetWidth(image.CGImage); CGFloat fixelH = CGImageGetHeight(image.CGImage); CGFloat max=MAX(fixelW, fixelH); float scare=1.0; if(max>320.0){ scare=320.0/max; } CGSize newSize=CGSizeMake(fixelW*scare,fixelH*scare); UIGraphicsBeginImageContext(newSize); [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)]; UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); NSData *data= UIImageJPEGRepresentation(newImage,0.6); NSString *guid = [[NSProcessInfo processInfo] globallyUniqueString]; NSString *tmpFile = [NSString stringWithFormat:@"image_picker_%@", guid]; NSString* tmpPath= [cacheDirectory stringByAppendingPathComponent:tmpFile]; [data writeToFile:tmpPath atomically:YES]; dispatch_async(dispatch_get_main_queue(), ^{ NSMutableArray*arr=self.finalMap[@"GengmeiAlbum"]; if(arr==nil){ self.finalMap[@"GengmeiAlbum"]=[NSMutableArray new]; } NSMutableDictionary * dict=[[NSMutableDictionary alloc] init]; [dict setObject:tmpPath forKey:@"path"]; [dict setObject:@"F" forKey:@"isVideo"]; [dict setObject:[NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]*1000] forKey:@"dataToken"]; [dict setObject:@"GengmeiAlbum" forKey:@"folderName"]; [self.finalMap[@"GengmeiAlbum"] insertObject:dict atIndex:0]; [self.finalMap[@"IsGengmeiAlbumAllImages"] insertObject:dict atIndex:0]; [self.takePhotoMap setObject:tempTake forKey:tmpPath]; [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:self.nativeCameraKey] :dict]; }); }); }else { NSLog(@"TACK PIC ERROR"); dispatch_async(dispatch_get_main_queue(), ^{ [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:self.nativeCameraKey] :nil]; }); } } - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { NSLog(@"imagePickerController"); UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; UIImageWriteToSavedPhotosAlbum(image, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil); [picker dismissViewControllerAnimated:YES completion:nil]; } // 取消选取调用的方法 - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { [viewController dismissViewControllerAnimated:YES completion:nil]; [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:self.nativeCameraKey] :nil]; } CFAbsoluteTime startTime; -(void)scanPhone:(long)resultId{ self.quitPage=false; if (self.finishScanImg) { [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:resultId] :self.finalMap]; return; } startTime=CFAbsoluteTimeGetCurrent(); if (self.finalMap==nil) { self.finalMap=[NSMutableDictionary dictionary]; } if(self.finalMapTemp==nil){ self.finalMapTemp=[NSMutableDictionary dictionary]; } if(self.scanMap==nil){ self.scanMap=[NSMutableDictionary dictionary]; } if(self.takePhotoMap==nil){ self.takePhotoMap=[NSMutableDictionary dictionary]; } if(self.channelList==nil){ self.channelList=[[NSMutableArray alloc] init]; } [self.channelList removeAllObjects]; [self.finalMap removeAllObjects]; [self.finalMapTemp removeAllObjects]; [self.scanMap removeAllObjects]; [self.takePhotoMap removeAllObjects]; self.nowSize=0; self.needSize=0; [assetCollectionList removeAllObjects]; // [NSThread detachNewThreadSelector:@selector(thread:) toTarget:self withObject:[NSString stringWithFormat:@"%ld",resultId]]; dispatch_async(queue, ^{ [self scanPhoneImage]; [self copyImg:resultId]; }); } - (void)enumerateAssetsInAssetCollection:(PHAssetCollection *)assetCollection original:(BOOL)original { NSLog(@"相簿名:%@", assetCollection.localizedTitle); PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init]; // 同步获得图片, 只会返回1张图片 options.synchronous = YES; // 获得某个相簿中的所有PHAsset对象 PHFetchResult *assets = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil]; for (PHAsset *asset in assets) { // 是否要原图 CGSize size = original ? CGSizeMake(asset.pixelWidth, asset.pixelHeight) : CGSizeZero; // 从asset中获得图片 [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) { NSLog(@"%@", result); }]; } } -(void)scanPhoneImage{ // PHFetchResult *favoritesCollection = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumFavorites options:nil]; // 获得相机胶卷 PHFetchResult *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil]; // 获得全部相片 PHFetchResult *cameraRolls = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil]; for (PHAssetCollection *collection in cameraRolls) { AlbumItem *model = [[AlbumItem alloc] init]; model.collection = collection; if (model.collectionNumber !=0) { [assetCollectionList addObject:model]; } } for (PHAssetCollection *collection in favoritesCollection) { AlbumItem *model = [[AlbumItem alloc] init]; model.collection = collection; if (model.collectionNumber !=0) { [assetCollectionList addObject:model]; } } for (PHAssetCollection *collection in assetCollections) { AlbumItem *model = [[AlbumItem alloc] init]; model.collection = collection; if (model.collectionNumber!=0) { [assetCollectionList addObject:model]; } } for (AlbumItem* item in assetCollectionList) { self.needSize+=[item collectionNumber]; } NSMutableArray * arr=self.finalMap[@"IsGengmeiAlbumAllImages"]; if (arr==nil) { self.finalMap[@"IsGengmeiAlbumAllImages"]=[NSMutableArray array]; } NSMutableArray *arrTemp=self.finalMapTemp[@"IsGengmeiAlbumAllImages"]; if(arrTemp==nil){ self.finalMapTemp[@"IsGengmeiAlbumAllImages"]=[NSMutableArray array]; for (int i=0; i>>> UP IMG"); _eventSink(self.finalMap); } }); } -(void)reslutImg:(long)resultId{ dispatch_async(dispatch_get_main_queue(), ^{ if(!self.quitPage){ NSLog(@"LSY=====>>>> RESULT IMG"); [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:resultId] :self.finalMapTemp]; } }); } -(void)reslutImgFinalMap:(long)resultId{ dispatch_async(dispatch_get_main_queue(), ^{ if(!self.quitPage){ NSLog(@"LSY=====>>>> RESULT IMG"); [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:resultId] :self.finalMap]; } }); } -(void) saveItemAndUpload:(NSMutableDictionary*)queryItemDict :(PHAsset*)assets :(NSString*)tmpPath :(NSString*)docName :(long)resultId{ NSLog(@"RUNNING THREAD %@",[NSThread currentThread]); NSLog(@"SCARE SIZEEE %d %d %d",self.nowSize,self.copySize,self.needSize); @synchronized (self) { self.nowSize++; [self.scanMap setObject:assets forKey:tmpPath]; NSMutableArray * arr=self.finalMap[docName]; if (arr==nil) { self.finalMap[docName]=[NSMutableArray array]; [self.finalMap[docName] addObject:queryItemDict]; }else{ [self.finalMap[docName] addObject:queryItemDict]; } bool haveIt=false; NSMutableArray * allArr=self.finalMap[@"IsGengmeiAlbumAllImages"]; for (int x=0; x<[allArr count]; x++) { NSString * inPath=allArr[x][@"path"]; NSString* outPath=queryItemDict[@"path"]; if ([inPath isEqualToString:outPath]) { haveIt=true; break; } } if(!haveIt){ [self.finalMap[@"IsGengmeiAlbumAllImages"] addObject:queryItemDict]; } if(self.needSize>260){ if(self.copySize<=261){ NSMutableArray * arr=self.finalMapTemp[docName]; if (arr==nil) { self.finalMapTemp[docName]=[NSMutableArray array]; [self.finalMapTemp[docName] addObject:queryItemDict]; }else{ [self.finalMapTemp[docName] addObject:queryItemDict]; } [self.finalMapTemp[@"IsGengmeiAlbumAllImages"] insertObject:queryItemDict atIndex:self.nowSize-1]; } if(self.copySize==261){ [self reslutImg:resultId]; }else if(self.nowSize==self.needSize){ self.finishScanImg=true; CFAbsoluteTime linkTime = (CFAbsoluteTimeGetCurrent() - startTime); NSLog(@"IOS COPY IMAGE 时间:%f ms",linkTime *1000.0); if(self.copySize<261){ [self reslutImgFinalMap:resultId]; }else{ [self upImgs]; } } }else{ if (self.nowSize==self.needSize) { self.finishScanImg=true; CFAbsoluteTime linkTime = (CFAbsoluteTimeGetCurrent() - startTime); NSLog(@"IOS COPY IMAGE 时间:%f ms",linkTime *1000.0); [self reslutImgFinalMap:resultId]; } } } } -(void)imageOnThread:(NSMutableDictionary*)dict{ PHAsset *assets=dict[@"assets"]; UIImage*result=dict[@"result"]; NSString *tmpPath=dict[@"tmpPath"]; NSString*docName=dict[@"docName"]; long resultId=[dict[@"resultId"] longLongValue]; if(result!=nil){ @autoreleasepool{ NSData *data = UIImageJPEGRepresentation(result, 0.8) ; [data writeToFile:tmpPath atomically:YES]; data=nil; result=nil; } } NSMutableDictionary* queryItemDict = [NSMutableDictionary dictionary]; [queryItemDict setObject:tmpPath forKey:@"path"]; [queryItemDict setObject:@"F" forKey:@"isVideo"]; [queryItemDict setObject:[NSString stringWithFormat:@"%ld", (long)[assets.creationDate timeIntervalSince1970]*1000] forKey:@"dataToken"]; // self.copySize++; [self saveItemAndUpload:queryItemDict :assets :tmpPath :docName :resultId]; } -(void) copyImg:(long)resultId{ NSLog(@"START THREAD %@",[NSThread currentThread]); self.copySize=0; self.nowSize=0; PHImageRequestOptions *imageRequestOption = [[PHImageRequestOptions alloc] init]; imageRequestOption.synchronous =NO; imageRequestOption.networkAccessAllowed = YES; imageRequestOption.deliveryMode=PHImageRequestOptionsDeliveryModeHighQualityFormat; //PHImageRequestOptionsDeliveryModeHighQualityFormat。//PHImageRequestOptionsDeliveryModeFastFormat // imageRequestOption.deliveryMode=PHImageRequestOptionsDeliveryModeFastFormat; imageRequestOption.resizeMode=PHImageRequestOptionsResizeModeFast; imageRequestOption.version=PHImageRequestOptionsVersionUnadjusted;//PHImageManagerMaximumSize // PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init]; // options.version = PHImageRequestOptionsVersionCurrent; // options.networkAccessAllowed = true; // options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic; NSFileManager *fileManager = [NSFileManager defaultManager]; for (int j=0; j * assetResult =[item assets]; for (int i=0; i<[assetResult count]; i++) { NSString* docName=[item collectionTitle]; PHAsset * assets=[assetResult objectAtIndex:i]; NSString * imgName=[assets valueForKey:@"filename"]; if (imgName==nil) { NSLog(@"NEWWWW!!!!! image name is Null!!! "); NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)([[NSDate date] timeIntervalSince1970]*100000)]; imgName=[NSString stringWithFormat:@"IMG_%@",timeSp]; } NSString *tmpPath=[cacheDirectory stringByAppendingPathComponent:imgName]; if(assets.mediaType==PHAssetMediaTypeVideo){ if ([fileManager fileExistsAtPath:tmpPath]==YES){ // [[PHImageManager defaultManager]requestAVAssetForVideo:assets options:options resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) { // AVURLAsset *urlAsset = (AVURLAsset *)asset; NSString* during=[NSString stringWithFormat:@"%i",(int)(assets.duration*1000)]; NSMutableDictionary* queryItemDict = [NSMutableDictionary dictionary]; [queryItemDict setObject:during forKey:@"during"]; [queryItemDict setObject:tmpPath forKey:@"path"]; [queryItemDict setObject:@"T" forKey:@"isVideo"]; [queryItemDict setObject:[NSString stringWithFormat:@"%ld", (long)[assets.creationDate timeIntervalSince1970]*1000] forKey:@"dataToken"]; [self saveItemAndUpload:queryItemDict :assets :tmpPath :docName :resultId]; // }]; }else{ int picWidth=[assets pixelWidth]; int picHeight=[assets pixelHeight]; float tempScareSize=1; if(picWidth>picHeight){ if (picWidth>320.0) { tempScareSize=320.0/picWidth; } }else{ if (picHeight>320.0) { tempScareSize=320.0/picHeight; } } CGSize temp=CGSizeMake(picWidth*tempScareSize, picHeight*tempScareSize); [[PHImageManager defaultManager] requestImageForAsset:assets targetSize:temp contentMode:PHImageContentModeDefault options:imageRequestOption resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) { self.copySize++; @autoreleasepool{ NSData *data = UIImageJPEGRepresentation(result, 0.8) ; [data writeToFile:tmpPath atomically:YES]; data=nil; result=nil; } NSString* during=[NSString stringWithFormat:@"%i",(int)(assets.duration*1000)]; NSLog(@"DDDduring %@",during); NSMutableDictionary* queryItemDict = [NSMutableDictionary dictionary]; [queryItemDict setObject:during forKey:@"during"]; [queryItemDict setObject:tmpPath forKey:@"path"]; [queryItemDict setObject:@"T" forKey:@"isVideo"]; [queryItemDict setObject:[NSString stringWithFormat:@"%ld", (long)[assets.creationDate timeIntervalSince1970]*1000] forKey:@"dataToken"]; [self saveItemAndUpload:queryItemDict :assets :tmpPath :docName :resultId]; }]; } }else{ if ([fileManager fileExistsAtPath:tmpPath]==YES){ NSMutableDictionary* queryItemDict = [NSMutableDictionary dictionary]; [queryItemDict setObject:tmpPath forKey:@"path"]; [queryItemDict setObject:@"F" forKey:@"isVideo"]; [queryItemDict setObject:[NSString stringWithFormat:@"%ld", (long)[assets.creationDate timeIntervalSince1970]*1000] forKey:@"dataToken"]; [self saveItemAndUpload:queryItemDict :assets :tmpPath :docName :resultId]; }else{ int picWidth=[assets pixelWidth]; int picHeight=[assets pixelHeight]; float tempScareSize=1; if(picWidth>picHeight){ if (picWidth>320.0) { tempScareSize=320.0/picWidth; } }else{ if (picHeight>320.0) { tempScareSize=320.0/picHeight; } } CGSize temp=CGSizeMake(picWidth*tempScareSize, picHeight*tempScareSize); [[PHImageManager defaultManager] requestImageForAsset:assets targetSize:temp contentMode:PHImageContentModeDefault options:imageRequestOption resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) { self.copySize++; @autoreleasepool{ NSData *data = UIImageJPEGRepresentation(result, 0.8) ; [data writeToFile:tmpPath atomically:YES]; data=nil; result=nil; } NSMutableDictionary* queryItemDict = [NSMutableDictionary dictionary]; [queryItemDict setObject:tmpPath forKey:@"path"]; [queryItemDict setObject:@"F" forKey:@"isVideo"]; [queryItemDict setObject:[NSString stringWithFormat:@"%ld", (long)[assets.creationDate timeIntervalSince1970]*1000] forKey:@"dataToken"]; // self.copySize++; [self saveItemAndUpload:queryItemDict :assets :tmpPath :docName :resultId]; }]; } } } } } -(NSString*) getVideoDuring:(CMTime)duration{ NSUInteger videoDurationSeconds = CMTimeGetSeconds(duration); NSUInteger dMinutes = floor(videoDurationSeconds % 3600 / 60); NSUInteger dSeconds = floor(videoDurationSeconds % 3600 % 60); if(dMinutes>99){ dMinutes=99; } NSString *videoDurationText = [NSString stringWithFormat:@"%02i:%02i", dMinutes, dSeconds]; NSLog(@"ISVIDEO DURING %@",videoDurationText); return videoDurationText; } -(void)popWindow:(NSString*)str{ UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:str preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { NSLog(@"确定"); }]; [alertController addAction:okAction]; [viewController presentViewController:alertController animated:YES completion:nil]; } //-(void)execRealImg:(long)resultId{ // dispatch_queue_t queue = dispatch_queue_create("execRealImg", DISPATCH_QUEUE_CONCURRENT); // self.nowSize=0; // self.copySize=0; // NSString *cacheDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]; // // NSFileManager *fileManager = [NSFileManager defaultManager]; // for (int j=0; j * assetResult =[item assets]; // for (int i=0; i<[assetResult count]; i++) { // if(self.quitPage){ // return; // } // __block NSString* docName=[item collectionTitle]; // PHAsset * assets=[assetResult objectAtIndex:i]; // __block NSString * imgName=[assets valueForKey:@"filename"]; // NSString * imgRealName=[NSString stringWithFormat:@"%@_REAL",imgName]; // if (imgName==nil) { // NSLog(@"NEWWWW!!!!! image name is Null!!! "); // NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)([[NSDate date] timeIntervalSince1970]*100000)]; // imgName=[NSString stringWithFormat:@"IMG_%@",timeSp]; // imgRealName=[NSString stringWithFormat:@"REAL_PATH_IMG_%@",timeSp]; // } // __block NSString *realPath=[cacheDirectory stringByAppendingPathComponent:imgRealName]; // NSLog(@"REALLL %@",realPath); // __block NSString *tmpPath=[cacheDirectory stringByAppendingPathComponent:imgName]; // if ([fileManager fileExistsAtPath:realPath]==YES){ // self.nowSize++; // NSLog(@"!!!REAL IS EXIE!! %@",realPath); // [self searchPath:realPath :tmpPath :docName]; // NSLog(@"SIZEEE %d %d ",self.nowSize,self.needSize); // if (self.nowSize==self.needSize) { // // [self upImgs]; // [self reslutImg:resultId]; // self.finishScanImg=true; // } // }else{ // NSLog(@"file NOT EXIT !! %@",realPath); // dispatch_async(queue, ^{ // if(assets.mediaType==PHAssetMediaTypeVideo){ // PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init]; // options.version = PHImageRequestOptionsVersionCurrent; // options.networkAccessAllowed = true; // options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic; // [[PHImageManager defaultManager]requestAVAssetForVideo:assets options:options resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) { // self.nowSize++; // AVURLAsset *urlAsset = (AVURLAsset *)asset; // NSString* videoUrl=[NSString stringWithFormat:@"%@",urlAsset.URL]; // [self searchPath:videoUrl :tmpPath :docName]; // if (self.nowSize==self.needSize) { // [self upImgs]; // // [self reslutImg:resultId]; // self.finishScanImg=true; // // } // }]; // }else{ // PHImageRequestOptions *imageRequestOption = [[PHImageRequestOptions alloc] init]; // imageRequestOption.synchronous =NO; // int picWidth=[assets pixelWidth]; // int picHeight=[assets pixelHeight]; // float tempScareSize=1; // float limit=1560.0; // if(picWidth>picHeight){ // if (picWidth>limit) { // tempScareSize=limit/picWidth; // } // }else{ // if (picHeight>limit) { // tempScareSize=limit/picHeight; // } // } // NSLog(@"SCARE SZIE %d %d %f %f %f",picWidth,picHeight,tempScareSize,picWidth*tempScareSize,picHeight*tempScareSize); // CGSize temp=CGSizeMake(picWidth*tempScareSize, picHeight*tempScareSize); // imageRequestOption.networkAccessAllowed = YES; // imageRequestOption.deliveryMode=PHImageRequestOptionsDeliveryModeHighQualityFormat; // // imageRequestOption.deliveryMode=PHImageRequestOptionsDeliveryModeFastFormat; // imageRequestOption.resizeMode=PHImageRequestOptionsResizeModeFast; // imageRequestOption.version=PHImageRequestOptionsVersionUnadjusted; // [[PHImageManager defaultManager] requestImageDataForAsset:assets options:imageRequestOption resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) { // self.nowSize++; // self.copySize++; // NSString* finalRealPath; // if([info objectForKey:@"PHImageFileURLKey"]){ // NSURL * path=[info objectForKey:@"PHImageFileURLKey"]; // NSLog(@"PATHHHH %@",path); // finalRealPath=[NSString stringWithFormat:@"%@",path]; // }else{ // NSLog(@"NOT HAVE IT!!! %@",realPath); // [imageData writeToFile:realPath atomically:YES]; // finalRealPath=realPath; // } // [self searchPath:finalRealPath :tmpPath :docName]; // NSLog(@"SIZEEE %d %d %d",self.nowSize,self.needSize,self.copySize); // if (self.nowSize==self.needSize) { // [self upImgs]; // // [self reslutImg:resultId]; // self.finishScanImg=true; // } // // else if(self.copySize%100==0||self.copySize==50){ // // [self upImgs]; // // } // }]; // } // }); // } // } // } //} //-(void)searchPath:(NSString*)finalRealPath :(NSString*)tmpPath :(NSString*)docName{ // NSMutableArray*>* array=self.finalMap[docName]; // for (int x=0; x<[array count]; x++) { // NSMutableDictionary* map=[array objectAtIndex:x]; // NSString* index=[map objectForKey:@"path"]; // if ([index isEqualToString:tmpPath]) { // [map setObject:finalRealPath forKey:@"realPath"]; // break; // } // } //} -(void)writeImage:(UIImage *)image dest:(NSString*)path{ @autoreleasepool { CFURLRef url=(__bridge CFURLRef)[NSURL fileURLWithPath:path]; CGImageDestinationRef des=CGImageDestinationCreateWithURL(url, CFSTR("public.png"), 1, NULL); if(!des){ NSLog(@"wrong"); return; } CGImageDestinationAddImage(des, image.CGImage, nil); if(!CGImageDestinationFinalize(des)){ NSLog(@"wrong222"); } CFRelease(des); } } - (UIImage *)image:(UIImage*)image byScalingToSize:(CGSize)targetSize { UIImage *sourceImage = image; UIImage *newImage = nil; UIGraphicsBeginImageContext(targetSize); CGRect thumbnailRect = CGRectZero; thumbnailRect.origin = CGPointZero; thumbnailRect.size.width = targetSize.width; thumbnailRect.size.height = targetSize.height; [sourceImage drawInRect:thumbnailRect]; newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage ; } -(NSData *)compressWithLengthLimit:(UIImage*) img max:(NSUInteger)maxLength{ // Compress by quality CGFloat compression = 1; NSData *data = UIImageJPEGRepresentation(img, compression); //NSLog(@"Before compressing quality, image size = %ld KB",data.length/1024); if (data.length < maxLength) return data; CGFloat max = 1; CGFloat min = 0; for (int i = 0; i < 6; ++i) { compression = (max + min) / 2; data = UIImageJPEGRepresentation(img, compression); //NSLog(@"Compression = %.1f", compression); //NSLog(@"In compressing quality loop, image size = %ld KB", data.length / 1024); if (data.length < maxLength * 0.9) { min = compression; } else if (data.length > maxLength) { max = compression; } else { break; } } //NSLog(@"After compressing quality, image size = %ld KB", data.length / 1024); if (data.length < maxLength) return data; UIImage *resultImage = [UIImage imageWithData:data]; // Compress by size NSUInteger lastDataLength = 0; while (data.length > maxLength && data.length != lastDataLength) { lastDataLength = data.length; CGFloat ratio = (CGFloat)maxLength / data.length; //NSLog(@"Ratio = %.1f", ratio); CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)), (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank UIGraphicsBeginImageContext(size); [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)]; resultImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); data = UIImageJPEGRepresentation(resultImage, compression); //NSLog(@"In compressing size loop, image size = %ld KB", data.length / 1024); } //NSLog(@"After compressing size loop, image size = %ld KB", data.length / 1024); return data; } - (NSMutableDictionary*)useToFetchCollection { NSMutableDictionary* queryItemDict = [NSMutableDictionary dictionary]; PHFetchResult * collectionResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeMoment subtype:PHAssetCollectionSubtypeSmartAlbumFavorites options:nil]; if (collectionResult.count == 0) { return queryItemDict; } PHFetchOptions *option = [[PHFetchOptions alloc] init]; //ascending 为YES时,按照照片的创建时间升序排列;为NO时,则降序排列 option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]]; PHAssetCollection* item=[collectionResult objectAtIndex:1]; [collectionResult enumerateObjectsWithOptions:option usingBlock:^(PHAssetCollection * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { NSLog(@"%@--%@--%@", obj.localIdentifier, obj.localizedTitle,obj); PHFetchResult * assetResult = [PHAsset fetchAssetsInAssetCollection:obj options:NO]; NSLog(@"INITTT %d",collectionResult.count); //HashMap>> for (int i=0; i<[assetResult count]; i++) { PHAsset * assets=[assetResult objectAtIndex:i]; NSArray* tempArray=[NSArray array]; if (assets.mediaType != PHAssetMediaTypeVideo){ } [[PHImageManager defaultManager] requestImageForAsset:assets targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeDefault options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) { // NSLog(@"INITTT___))))00000 %d %d %@",i,[assetResult count],info); NSURL * url = [info objectForKey:@"PHImageFileURLKey"]; NSLog(@"INITTT___))))00000 %@",url); NSData *data = [NSData dataWithContentsOfURL:url]; UIImage* image = [UIImage imageWithData:data]; // CGSize size; // if(image) // { // size = image.size; // } // NSLog(@"INFO %d",size); NSString *guid = [[NSProcessInfo processInfo] globallyUniqueString]; NSString *tmpFile = [NSString stringWithFormat:@"image_picker_%@.JPG", guid]; // NSString *tmpDirectory = NSHomeDirectory(); NSString *tmpDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]; // NSString *tmpDirectory = NSTemporaryDirectory(); NSString *tmpPath = [tmpDirectory stringByAppendingPathComponent:tmpFile]; if ([[NSFileManager defaultManager] createFileAtPath:tmpPath contents:data attributes:nil]) { NSLog(@"result %@",tmpPath); } else { NSLog(@"ERRORRRR "); } // NSLog(@"YEEEEEEE %@",url); }]; } }]; return queryItemDict; } - (void) findAllFiles{ NSFileManager *fileManager = [NSFileManager defaultManager]; //在这里获取应用程序Documents文件夹里的文件及文件夹列表 // NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //         NSString *documentDir = [documentPaths objectAtIndex:0]; // NSString *tmpDirectory = NSTemporaryDirectory(); // NSString *tmpDirectory = NSHomeDirectory(); NSString *tmpDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]; NSError *error = nil;  NSArray *fileList = [[NSArray alloc] init]; //fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组 fileList = [fileManager contentsOfDirectoryAtPath:tmpDirectory error:&error]; NSMutableArray *dirArray = [[NSMutableArray alloc] init]; //在上面那段程序中获得的fileList中列出文件夹名 for (NSString *file in fileList) { NSString *path = [tmpDirectory stringByAppendingPathComponent:file]; NSLog(@"patH!!! %@",path); } } - (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments eventSink:(FlutterEventSink)events{ NSLog(@"QWEQWEQEW"); _eventSink = events; return nil; } - (FlutterError* _Nullable)onCancelWithArguments:(id _Nullable)arguments{ _eventSink = nil; NSLog(@"QWEQWEQEW"); return nil; } @end