Exemple #1
0
        // Requests all album and smart albums collections to be fetched.
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // TODO: https://trello.com/c/ZLOvAFWp
            PHPhotoLibrary.RequestAuthorization(status => {
                if (status != PHAuthorizationStatus.Authorized)
                {
                    return;
                }

                // Fetch all albums
                var allAlbums = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.Album, PHAssetCollectionSubtype.Any, null)
                                .Cast <PHAssetCollection> ();
                albums.AddRange(allAlbums);

                // Fetch all smart albums
                var smartAlbums = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.SmartAlbum, PHAssetCollectionSubtype.Any, null)
                                  .Cast <PHAssetCollection> ();
                albums.AddRange(smartAlbums);

                // Ask the collection view to reload data, so the fetched albums is displayed.
                NSOperationQueue.MainQueue.AddOperation(() => {
                    CollectionView?.ReloadData();
                });
            });
        }
        static private IEnumerable <PLAsset> GetPhotosToBeBackedUp()
        {
            if (PHPhotoLibrary.AuthorizationStatus != PHAuthorizationStatus.Authorized)
            {
                yield break;
                //return null;
            }

            var collections = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.SmartAlbum, PHAssetCollectionSubtype.SmartAlbumUserLibrary, null);
            var photos      = collections.OfType <PHAssetCollection>().SelectMany(x => PHAsset.FetchAssets(x, null).OfType <PHAsset>().Select(x => {
                var asset = new PLAsset {
                    Asset = x,
                    Id    = x.LocalIdentifier
                };
                return(asset);
            })).ToList();

            foreach (var asset in Globals.Database.Table <PLAsset>())
            {
                if (photos.Contains(asset))
                {
                    photos.Remove(asset);
                }
            }
            foreach (var item in photos)
            {
                item.PopulateProperties();
                yield return(item);
            }
            //return photos.AsReadOnly();
        }
Exemple #3
0
        void SetupAlbum()
        {
            var album = PHAssetCollection.FetchAssetCollections(new[] { Xamarin.Essentials.Preferences.Get("iOSAlbumIdentifier", string.Empty).ToString() }, null)?.firstObject as PHAssetCollection;

            if (album == null)
            {
                var albums = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.Album, PHAssetCollectionSubtype.Any, new PHFetchOptions
                {
                    IncludeAssetSourceTypes = PHAssetSourceType.UserLibrary
                });
                if (albums.Count > 0)
                {
                    foreach (var a in albums)
                    {
                        var collection = (a as PHAssetCollection);
                        if (collection.LocalizedTitle.Equals("ConferenceVision"))
                        {
                            SaveIdentifier(collection.LocalIdentifier);
                            return;
                        }
                    }
                }
                PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() =>
                {
                    var req         = PHAssetCollectionChangeRequest.CreateAssetCollection("ConferenceVision");
                    albumIdentifier = req.PlaceholderForCreatedAssetCollection.LocalIdentifier;
                    SaveIdentifier(albumIdentifier);
                }, (success, error) =>
                {
                    Debug.Write("Create Album " + success);
                });
            }
        }
        private static PHAssetCollection FindOrCreateAlbum(string albumName)
        {
            var albums      = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.Album, PHAssetCollectionSubtype.AlbumRegular, null);
            var customAlbum = (PHAssetCollection)albums.FirstOrDefault(s => ((PHAssetCollection)s).LocalizedTitle.Equals(albumName));

            if (customAlbum == null)
            {
                var success = PHPhotoLibrary.SharedPhotoLibrary.PerformChangesAndWait(
                    () =>
                {
                    PHAssetCollectionChangeRequest.CreateAssetCollection(albumName);
                }, out var error
                    );
                if (success)
                {
                    albums      = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.Album, PHAssetCollectionSubtype.AlbumRegular, null);
                    customAlbum = (PHAssetCollection)albums.FirstOrDefault(s => ((PHAssetCollection)s).LocalizedTitle.Equals(albumName));
                }
                else
                {
                    Console.WriteLine(error);
                    customAlbum = null;
                }
            }

            return(customAlbum);
        }
Exemple #5
0
        public override void AwakeFromNib()
        {
            // Create a PHFetchResult object for each section in the table view.
            var allPhotosOptions = new PHFetchOptions();

            allPhotosOptions.SortDescriptors = new [] {
                new NSSortDescriptor("creationDate", true)
            };

            PHFetchResult allPhotos   = PHAsset.FetchAssets(allPhotosOptions);
            PHFetchResult smartAlbums = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.SmartAlbum,
                                                                                PHAssetCollectionSubtype.AlbumRegular, null);

            PHFetchResult topLevelUserCollections = PHCollection.FetchTopLevelUserCollections(null);

            // Store the PHFetchResult objects and localized titles for each section.
            sectionFetchResults = new [] {
                allPhotos, smartAlbums, topLevelUserCollections
            };

            sectionLocalizedTitles = new [] {
                string.Empty, "Smart Albums", "Albums", string.Empty
            };

            PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver(this);
        }
        public static bool SaveImageToGalery(string imagePath, string albumName)
        {
            var saved = true;
            PHAssetCollection customAlbum = null;

            if (!string.IsNullOrEmpty(albumName))
            {
                customAlbum = FindOrCreateAlbum(albumName);
                if (customAlbum == null)
                {
                    return(false);
                }
            }

            PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(
                () =>
            {
                var assetRequest = PHAssetChangeRequest.FromImage(NSUrl.FromFilename(imagePath));
                if (customAlbum != null)
                {
                    var albumRequest = PHAssetCollectionChangeRequest.ChangeRequest(customAlbum);
                    albumRequest?.AddAssets(new[] { assetRequest.PlaceholderForCreatedAsset });
                }
            },
                (success, error) =>
            {
                if (!success)
                {
                    Console.WriteLine(error);
                    saved = success;
                }
            }
                );
            return(saved);
        }
Exemple #7
0
        void SaveToAlbum(string watermarkedPath)
        {
            var lib = PHPhotoLibrary.SharedPhotoLibrary;

            lib.PerformChanges(() =>
            {
                var album             = PHAssetCollection.FetchAssetCollections(new[] { Xamarin.Essentials.Preferences.Get("iOSAlbumIdentifier", string.Empty) }, null)?.firstObject as PHAssetCollection;
                var collectionRequest = PHAssetCollectionChangeRequest.ChangeRequest(album);

                if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
                {
                    var options = new PHAssetResourceCreationOptions
                    {
                        ShouldMoveFile = true
                    };
                    var changeRequest = PHAssetCreationRequest.CreationRequestForAsset();
                    changeRequest.AddResource(PHAssetResourceType.Video, NSUrl.FromString(watermarkedPath), options);

                    collectionRequest.AddAssets(new[] { changeRequest.PlaceholderForCreatedAsset });
                }
                else
                {
                    var changeRequest2 = PHAssetChangeRequest.FromVideo(NSUrl.FromString(watermarkedPath));
                    collectionRequest.AddAssets(new[] { changeRequest2.PlaceholderForCreatedAsset });
                }

                RetrieveLastAssetSaved();
            }, (success, err) =>
            {
            });
        }
Exemple #8
0
        private void FeetchAddPhotos()
        {
            PHPhotoLibrary.RequestAuthorization(status =>
            {
                if (status != PHAuthorizationStatus.Authorized)
                {
                    return;
                }

                var galleryTemp = new List <PHAssetCollection>();

                var allAlbums   = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.Album, PHAssetCollectionSubtype.Any, null).Cast <PHAssetCollection>();
                var smartAlbums = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.SmartAlbum, PHAssetCollectionSubtype.SmartAlbumUserLibrary, null).Cast <PHAssetCollection>();

                galleryTemp.AddRange(allAlbums);
                galleryTemp.AddRange(smartAlbums);

                var gallerySort = galleryTemp.OrderBy(obj => obj.LocalizedTitle);

                NSOperationQueue.MainQueue.AddOperation(() =>
                {
                    foreach (var itemRaw in gallerySort)
                    {
                        var sortOptions             = new PHFetchOptions();
                        sortOptions.SortDescriptors = new NSSortDescriptor[] { new NSSortDescriptor("creationDate", false) };

                        var items = PHAsset.FetchAssets(itemRaw, sortOptions).Cast <PHAsset>().ToList();

                        if (items.Count > 0)
                        {
                            var colec = new GalleryNative()
                            {
                                Collection = itemRaw,
                            };
                            colec.Images.Add(new PhotoSetNative());

                            foreach (var item in items)
                            {
                                var newPhoto = new PhotoSetNative();
                                newPhoto.galleryImageXF.OriginalPath = item.LocalIdentifier;
                                newPhoto.Image = item;
                                colec.Images.Add(newPhoto);
                            }
                            galleryDirectories.Add(colec);
                        }
                    }

                    tableView.ReloadData();

                    if (galleryDirectories.Count > 0)
                    {
                        CurrentParent = 0;
                        IF_ItemSelectd(CurrentParent);
                    }
                });
            });
        }
Exemple #9
0
        public static Task <PHAssetCollection> GetAlbum(string name)
        {
            var options = new PHFetchOptions();

            options.Predicate = NSPredicate.FromFormat("title = %@", NSObject.FromObject(name));
            var collection = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.Album, PHAssetCollectionSubtype.Any, options);

            return(collection.firstObject != null
                ? Task.FromResult((PHAssetCollection)collection.firstObject)
                : CreateAlbum(name));
        }
Exemple #10
0
        public void Test()
        {
            // Fetch PHAssetCollections
            var topLevelUserCollections = PHCollection.FetchTopLevelUserCollections(null);
            var smartAlbums             = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.SmartAlbum, PHAssetCollectionSubtype.AlbumRegular, null);

            _collectionsFetchResults = new List <PHFetchResult> {
                topLevelUserCollections, smartAlbums
            };
            _collectionsLocalizedTitles = new List <string> {
                "picker.table.user-albums-header".Translate(defaultValue: "Albums"), "picker.table.smart-albums-header".Translate("Smart Albums")
            };

            UpdateFetchResults();
        }
Exemple #11
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            NavigationItem.RightBarButtonItem = new UIBarButtonItem(UIBarButtonSystemItem.Add, AddAlbum);

            // Create a PHFetchResult object for each section in the table view.
            var allPhotosOptions = new PHFetchOptions {
                SortDescriptors = new NSSortDescriptor [] { new NSSortDescriptor("creationDate", true) },
            };

            allPhotos       = PHAsset.FetchAssets(allPhotosOptions);
            smartAlbums     = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.SmartAlbum, PHAssetCollectionSubtype.AlbumRegular, null);
            userCollections = PHCollection.FetchTopLevelUserCollections(null);

            PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver(this);
        }
        public void Update(Action handler = null)
        {
            List <PHFetchResult> albumListFetchResult = new List <PHFetchResult>();

            InvokeInBackground(() =>
            {
                foreach (var type in _assetCollectionTypes)
                {
                    albumListFetchResult.AddRange(new List <PHFetchResult> {
                        PHAssetCollection.FetchAssetCollections(type, PHAssetCollectionSubtype.Any, null)
                    });
                }

                this._albumList  = new List <Item>();
                var tmpAlbumList = new List <Item>();
                var isAssetCollectionSubtypeAny = this._assetCollectionSubtypes.Contains(PHAssetCollectionSubtype.Any);

                foreach (var fetchResult in albumListFetchResult)
                {
                    fetchResult.Enumerate((NSObject album, nuint index, out bool stop) =>
                    {
                        var phAlbum = album as PHAssetCollection;
                        if (this._assetCollectionSubtypes.Contains((album as PHAssetCollection).AssetCollectionSubtype) || isAssetCollectionSubtypeAny)
                        {
                            if (this._shouldShowEmptyAlbum || PHAsset.FetchAssets((album as PHAssetCollection), PhotoKitAssetList.FetchOptions(this._mediaType)).Count() != 0)
                            {
                                tmpAlbumList.Add(new PhotoKitAssetList(album as PHAssetCollection, this._mediaType));
                            }
                        }

                        stop = false;
                    });
                }

                if (this._assetCollectionTypes.Count() == 1 && this._assetCollectionTypes.Contains(PHAssetCollectionType.Moment))
                {
                    this._albumList = tmpAlbumList.OrderByDescending(x => x.Date.SecondsSinceReferenceDate).ToList();
                }
                else
                {
                    this._albumList = tmpAlbumList;
                }

                handler?.Invoke();
            });
        }
Exemple #13
0
        public async Task <IMediaAlbum[]> GetAlbumsAsync()
        {
            if (!await RequestAuthorizationAsync())
            {
                return(new IMediaAlbum[] { });
            }

            var list = new List <MediaAlbum>();

            var albums = new List <PHAssetCollection>();

            albums.AddRange(PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.Album, PHAssetCollectionSubtype.Any, null).Cast <PHAssetCollection>());
            albums.AddRange(PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.SmartAlbum, PHAssetCollectionSubtype.Any, null).Cast <PHAssetCollection>());

            return(albums.Select(col => new MediaAlbum(col))
                   .OrderBy(a => a.Title)
                   .ToArray());
        }
Exemple #14
0
        public static async Task <bool> SaveToLibrary(string path, string albumName)
        {
            var source = new TaskCompletionSource <bool>();
            PHAssetCollection album = await GetAlbum(albumName);

            PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() =>
            {
                var assetReq    = PHAssetChangeRequest.FromImage(NSUrl.CreateFileUrl(path, null));
                var albumReq    = PHAssetCollectionChangeRequest.ChangeRequest(album);
                var placeholder = assetReq.PlaceholderForCreatedAsset;
                albumReq.AddAssets(new[] { (PHObject)placeholder });
            }, (success, err) =>
            {
                Debug.WriteLine($"SaveToLibrary: {success}");
                source.SetResult(success);
            });
            return(await source.Task);
        }
Exemple #15
0
        private static PHFetchResult FetchAssets()
        {
            const string sortType = "creationDate";

            var assetsOptions = new PHFetchOptions
            {
                SortDescriptors = new[]
                {
                    new NSSortDescriptor(sortType, false)
                },
                FetchLimit = FetchLimit
            };

            return(PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.SmartAlbum,
                                                           PHAssetCollectionSubtype.SmartAlbumUserLibrary, null).firstObject is PHAssetCollection assetCollection
                ? PHAsset.FetchAssets(assetCollection, assetsOptions)
                : PHAsset.FetchAssets(assetsOptions));
        }
Exemple #16
0
        public Task <IMediaAlbum> CreateAlbum(string title)
        {
            return(Task.Run(() =>
            {
                IMediaAlbum album = null;
                string id = null;
                if (PHPhotoLibrary.SharedPhotoLibrary.PerformChangesAndWait(() =>
                {
                    var request = PHAssetCollectionChangeRequest.CreateAssetCollection(title);
                    id = request.PlaceholderForCreatedAssetCollection.LocalIdentifier;
                }, out var error))
                {
                    var col = (PHAssetCollection)PHAssetCollection.FetchAssetCollections(new[] { id }, null).First();
                    album = new MediaAlbum(col);
                }

                return album;
            }));
        }
Exemple #17
0
        public static Task <PHAssetCollection> CreateAlbum(string name)
        {
            var source = new TaskCompletionSource <PHAssetCollection>();
            PHObjectPlaceholder placeholder = null;

            PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() =>
            {
                var request = PHAssetCollectionChangeRequest.CreateAssetCollection(name);
                placeholder = request.PlaceholderForCreatedAssetCollection;
            }, (success, err) =>
            {
                if (success)
                {
                    var result = PHAssetCollection.FetchAssetCollections(new[] { placeholder.LocalIdentifier }, null);
                    source.SetResult((PHAssetCollection)result.firstObject);
                }
                else
                {
                    source.SetException(new Exception(err.ToString()));
                }
            });
            return(source.Task);
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            PHPhotoLibrary.RequestAuthorization((status) => {
                if (status == PHAuthorizationStatus.Authorized)
                {
                    var result = PHAssetCollection.FetchTopLevelUserCollections(null);

                    var assetCollection = result.firstObject as PHAssetCollection;

                    var imageManager = new PHCachingImageManager();

                    var assets = PHAsset.FetchAssets(assetCollection, null);

                    var imageAsset = assets[6];

                    this.InvokeOnMainThread(() => {
                        imageManager.RequestImageForAsset((PHAsset)imageAsset, this.View.Frame.Size, PHImageContentMode.Default, null, new PHImageResultHandler(this.ImageReceived));
                    });
                }
            });
        }
 internal MediaAlbum(PHAssetCollection assetCollection)
 {
     AssetCollection = assetCollection;
 }
Exemple #20
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            _picker = (GMImagePickerController)NavigationController.ParentViewController;
            View.BackgroundColor = _picker.PickerBackgroundColor;

            // Navigation bar customization
            if (!string.IsNullOrWhiteSpace(_picker.CustomNavigationBarPrompt))
            {
                NavigationItem.Prompt = _picker.CustomNavigationBarPrompt;
            }

            _imageManager = new PHCachingImageManager();

            // Table view aspect
            TableView.RowHeight      = AlbumRowHeight;
            TableView.SeparatorStyle = UITableViewCellSeparatorStyle.None;
            TableView.Source         = new GMAlbumsViewTableViewSource(this);

            // Buttons
            var barButtonItemAttributes = new UITextAttributes
            {
                Font = UIFont.FromName(_picker.PickerFontName, _picker.PickerFontHeaderSize)
            };

            var cancelTitle = _picker.CustomCancelButtonTitle ?? "picker.navigation.cancel-button".Translate(defaultValue: "Cancel");

            NavigationItem.LeftBarButtonItem = new UIBarButtonItem(cancelTitle,
                                                                   UIBarButtonItemStyle.Plain,
                                                                   Dismiss);

            if (_picker.UseCustomFontForNavigationBar)
            {
                NavigationItem.LeftBarButtonItem.SetTitleTextAttributes(barButtonItemAttributes, UIControlState.Normal);
                NavigationItem.LeftBarButtonItem.SetTitleTextAttributes(barButtonItemAttributes, UIControlState.Highlighted);
            }

            if (_picker.AllowsMultipleSelection)
            {
                var doneTitle = _picker.CustomDoneButtonTitle ?? "picker.navigation.done-button".Translate(defaultValue: "Done");
                NavigationItem.RightBarButtonItem = new UIBarButtonItem(doneTitle,
                                                                        UIBarButtonItemStyle.Done,
                                                                        FinishPickingAssets);
                if (_picker.UseCustomFontForNavigationBar)
                {
                    NavigationItem.RightBarButtonItem.SetTitleTextAttributes(barButtonItemAttributes, UIControlState.Normal);
                    NavigationItem.RightBarButtonItem.SetTitleTextAttributes(barButtonItemAttributes, UIControlState.Highlighted);
                }
                NavigationItem.RightBarButtonItem.Enabled = !_picker.AutoDisableDoneButton || _picker.SelectedAssets.Any();
            }

            // Bottom toolbar
            ToolbarItems = _picker.GetToolbarItems();

            // Title
            Title = _picker.Title ?? "picker.navigation.title".Translate(defaultValue: "Navigation bar default title");

            // Fetch PHAssetCollections
            var topLevelUserCollections = PHCollection.FetchTopLevelUserCollections(null);
            var smartAlbums             = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.SmartAlbum, PHAssetCollectionSubtype.AlbumRegular, null);

            _collectionsFetchResults = new List <PHFetchResult> {
                topLevelUserCollections, smartAlbums
            };
            _collectionsLocalizedTitles = new List <string> {
                "picker.table.user-albums-header".Translate(defaultValue: "Albums"), "picker.table.smart-albums-header".Translate("Smart Albums")
            };

            UpdateFetchResults();

            // Register for changes
            PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver(this);
        }
Exemple #21
0
		public Task<string> SaveAsset (UIImage updatedSnapshot, PHAssetCollection bugTrapAlbum, TaskCompletionSource<string> tcs)
		{
			string newLocalIdentifier = null;

			PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() => {

				// create a new asset from the UIImage updatedSnapshot
				var createAssetRequest = PHAssetChangeRequest.FromImage(updatedSnapshot);

				// create a request to make changes to the bugTrap album
				var collectionRequest = PHAssetCollectionChangeRequest.ChangeRequest(bugTrapAlbum);

				// get a reference to the new localIdentifier
				newLocalIdentifier = createAssetRequest.PlaceholderForCreatedAsset.LocalIdentifier;

				// add the newly created asset to the bugTrap album
				collectionRequest.AddAssets(new [] { createAssetRequest.PlaceholderForCreatedAsset });

			}, (success, error) => {

				if (success) {

					if (!tcs.TrySetResult(newLocalIdentifier)) {
						var ex = new Exception ("UpdateAsset Failed");
						tcs.TrySetException(ex);
						// Log.Error(ex);
					}

				} else if (error != null) {
					// Log.Error("Photos", error);
					if (!tcs.TrySetResult(null)) {
						var ex = new Exception (error.LocalizedDescription);
						tcs.TrySetException(ex);
						// Log.Error(ex);
					}
				}
			});

			return tcs.Task;
		}
Exemple #22
0
        public async Task <string> ImageSave(MemoryStream stream, bool compatibleMode, string fileName = null)
        {
            NSError error = null;

            //虽然对于iOS没有这两个权限,但要保证方法异步,所以还是保留下来了
            await Permissions.RequestAsync <Permissions.StorageWrite>();

            await Permissions.RequestAsync <Permissions.StorageRead>();

            //判断相册是否存在,不存在就创建
            PHAssetCollection appAlbum = null;
            PHFetchResult     albums   = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.Album, PHAssetCollectionSubtype.Any, null);

            foreach (PHAssetCollection album in albums)
            {
                if (album.LocalizedTitle == albumName)
                {
                    appAlbum = album;
                }
            }
            if (appAlbum == null)   //相册不存在,新建
            {
                string[] albumID = new string[1];
                PHPhotoLibrary.SharedPhotoLibrary.PerformChangesAndWait(() =>
                {
                    albumID[0] = PHAssetCollectionChangeRequest.CreateAssetCollection(albumName).PlaceholderForCreatedAssetCollection.LocalIdentifier;
                }, out error);
                appAlbum = PHAssetCollection.FetchAssetCollections(albumID, null)[0] as PHAssetCollection;
            }

            //获取路径及名称
            string documentsPath;

            documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            if (fileName == null || fileName == "")
            {
                fileName = "Tank_" + DateTime.Now.ToLocalTime().ToString("yyyyMMdd_HHmmss") + ".png";
            }
            string path = Path.Combine(documentsPath, fileName);

            //保存
            FileStream photoTankFile = new FileStream(path, FileMode.Create);

            byte[] photoTank = stream.ToArray();
            photoTankFile.Write(photoTank, 0, photoTank.Length);
            photoTankFile.Flush();
            photoTankFile.Close();

            //如果是图片或视频,就添加到相册里
            string MimeType = MimeUtility.GetMimeMapping(path);

            if (MimeType.IndexOf("image") != -1 || MimeType.IndexOf("video") != -1)
            {
                string[] assetID = new string[1];
                PHPhotoLibrary.SharedPhotoLibrary.PerformChangesAndWait(() =>
                {
                    if (MimeType.IndexOf("image") != -1)
                    {
                        assetID[0] = PHAssetChangeRequest.FromImage(new NSUrl(path, true)).PlaceholderForCreatedAsset.LocalIdentifier;
                    }
                    if (MimeType.IndexOf("video") != -1)
                    {
                        assetID[0] = PHAssetChangeRequest.FromVideo(new NSUrl(path, true)).PlaceholderForCreatedAsset.LocalIdentifier;
                    }
                }, out error);
                PHAsset    asset = PHAsset.FetchAssetsUsingLocalIdentifiers(assetID, null)[0] as PHAsset;
                PHObject[] objs  = { asset };
                PHPhotoLibrary.SharedPhotoLibrary.PerformChangesAndWait(() =>
                {
                    PHAssetCollectionChangeRequest collectionChangeRequest = PHAssetCollectionChangeRequest.ChangeRequest(appAlbum);
                    collectionChangeRequest.InsertAssets(objs, new NSIndexSet(0));
                }, out error);
            }

            return(Path.Combine(fileName));
        }
        protected void Internal_FillCache()
        {
            if (_bCached)
            {
                return;
            }
            _globalLock.EnterWriteLock();

            try
            {
                if (_bCached)
                {
                    return;
                }

                var cacheDir    = new Dictionary <string, PHAssetCollection>();
                var cachePhoto  = new Dictionary <string, PHPhotoItem>();
                var collections = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.SmartAlbum, PHAssetCollectionSubtype.SmartAlbumUserLibrary, null);
                foreach (PHAssetCollection asset in collections)
                {
                    cacheDir["/" + asset.LocalizedTitle] = asset;

                    var assets = PHAsset.FetchAssets(asset, null);
                    foreach (PHAsset photo in assets)
                    {
                        var assetResources = PHAssetResource.GetAssetResources(photo);
                        var original       = assetResources.FirstOrDefault(x => x.ResourceType == PHAssetResourceType.Video ||
                                                                           x.ResourceType == PHAssetResourceType.Photo ||
                                                                           x.ResourceType == PHAssetResourceType.Audio);

                        if (original == null)
                        {
                            continue;
                        }

                        var   dt       = photo.CreationDate.ToDateTime();
                        var   dtstr    = dt.ToLocalTime().ToString("yyyy-MM-dd HH_mm");
                        var   filename = $"{dtstr} {original.OriginalFilename}";
                        UPath up       = Path.Combine(asset.LocalizedTitle, filename);
                        var   item     = new PHPhotoItem {
                            Col   = asset,
                            Asset = photo,
                            Res   = original
                        };
                        item.Path   = new Lazy <string>(item.FillPath);
                        item.Length = new Lazy <long>(item.FillLength);

                        cachePhoto[up.ToAbsolute().ToString().ToUpperInvariant()] = item;

                        var originalName = Path.GetFileNameWithoutExtension(original.OriginalFilename);
                        foreach (var resource in assetResources)
                        {
                            if (resource == original)
                            {
                                continue;
                            }
                            if (string.IsNullOrEmpty(resource.OriginalFilename))
                            {
                                continue;
                            }

                            var extension = Path.GetExtension(resource.OriginalFilename) ?? string.Empty;
                            var fileName  = $"{dtstr} {originalName} ({resource.ResourceType:G}){extension}";

                            up = Path.Combine(asset.LocalizedTitle, fileName);


                            item = new PHPhotoItem {
                                Col   = asset,
                                Asset = photo,
                                Res   = resource
                            };
                            item.Path   = new Lazy <string>(item.FillPath);
                            item.Length = new Lazy <long>(item.FillLength);

                            cachePhoto[up.ToAbsolute().ToString().ToUpperInvariant()] = item;
                        }
                    }
                }

                _cacheDir   = cacheDir;
                _cachePhoto = cachePhoto;
                _bCached    = true;
                Task.Run(() => {
                    Parallel.ForEach(cachePhoto, new ParallelOptions {
                        MaxDegreeOfParallelism = 2 * Environment.ProcessorCount
                    },
                                     x => {
                        _ = x.Value.Length.Value;
                        _ = x.Value.Path.Value;
                    });
                });
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                _globalLock.ExitWriteLock();
            }
        }
Exemple #24
0
 public PhotoKitAssetList(PHAssetCollection album, MediaType mediaType)
 {
     _assetList = album;
     _mediaType = mediaType;
     Update();
 }
Exemple #25
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            var rotateTap = new UITapGestureRecognizer(RotateTap);

            rotate.AddGestureRecognizer(rotateTap);

            var zoomTap = new UITapGestureRecognizer(ZoomTap);

            resize.AddGestureRecognizer(zoomTap);

            var multiselectTap = new UITapGestureRecognizer(MultiSelectTap);

            multiSelect.AddGestureRecognizer(multiselectTap);

            bottomArrow.Transform = CGAffineTransform.MakeRotation((float)(Math.PI));

            source = new PhotoCollectionViewSource(_m);
            photoCollection.Source = source;
            photoCollection.RegisterClassForCell(typeof(PhotoCollectionViewCell), nameof(PhotoCollectionViewCell));

            photoCollection.SetCollectionViewLayout(new UICollectionViewFlowLayout()
            {
                ItemSize                = Constants.CellSize,
                MinimumLineSpacing      = 1,
                MinimumInteritemSpacing = 1,
            }, false);

            delegateP = new PhotoCollectionViewFlowDelegate(source);
            photoCollection.Delegate = delegateP;

            delegateP.CellClicked += CellAction;

            _cropView = new CropView(new CGRect(0, 0, UIScreen.MainScreen.Bounds.Width, UIScreen.MainScreen.Bounds.Width));

            _cropView.ZoomingStarted += (object sender, UIScrollViewZoomingEventArgs e) =>
            {
                NavigationItem.RightBarButtonItem.Enabled = false;
            };

            _cropView.ZoomingEnded += (object sender, ZoomingEndedEventArgs e) =>
            {
                NavigationItem.RightBarButtonItem.Enabled = true;
            };

            var albums       = new List <PHAssetCollection>();
            var sortedAlbums = new List <Tuple <string, PHFetchResult> >();
            var fetchOptions = new PHFetchOptions();

            var allAlbums = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.Album, PHAssetCollectionSubtype.AlbumRegular, null)
                            .Cast <PHAssetCollection>();

            albums.AddRange(allAlbums);
            var smartAlbums = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.SmartAlbum, PHAssetCollectionSubtype.AlbumRegular, null)
                              .Cast <PHAssetCollection>();

            albums.AddRange(smartAlbums);
            fetchOptions.Predicate = NSPredicate.FromFormat("mediaType == %d", FromObject(PHAssetMediaType.Image));

            foreach (var item in albums)
            {
                var firstAsset = PHAsset.FetchAssets(item, fetchOptions);
                if (firstAsset.Count > 0)
                {
                    sortedAlbums.Add(new Tuple <string, PHFetchResult>(item.LocalizedTitle, firstAsset));
                }
            }

            sortedAlbums = sortedAlbums.OrderByDescending(a => a.Item2.Count).ToList();

            _modalFolderView.BackgroundColor = UIColor.White;

            var folderTable = new UITableView();

            folderTable.Bounces         = false;
            folderTable.AllowsSelection = false;
            folderTable.RowHeight       = 90;
            folderTable.SeparatorStyle  = UITableViewCellSeparatorStyle.None;
            var folderSource = new FolderTableViewSource(sortedAlbums);

            folderSource.CellAction += (ActionType arg1, Tuple <string, PHFetchResult> arg2) =>
            {
                TitleTapped();
                _titleLabel.Text = arg2.Item1;
                source.UpdateFetchResult(arg2.Item2);
                photoCollection.SetContentOffset(new CGPoint(0, 0), false);
                photoCollection.ReloadData();
                if (!source.MultiPickMode)
                {
                    delegateP.ItemSelected(photoCollection, NSIndexPath.FromItemSection(0, 0));
                }
            };
            folderTable.Source = folderSource;
            _modalFolderView.AddSubview(folderTable);
            folderTable.RegisterClassForCellReuse(typeof(AlbumTableViewCell), nameof(AlbumTableViewCell));
            folderTable.AutoPinEdgesToSuperviewEdges();
            folderTable.ReloadData();

            cropBackgroundView.BackgroundColor = Constants.R245G245B245;
            cropBackgroundView.AddSubview(_cropView);
            NavigationController.NavigationBar.Translucent = false;
            SetBackButton();

            _titleLabel.Text = sortedAlbums.FirstOrDefault()?.Item1;
            source.UpdateFetchResult(sortedAlbums.FirstOrDefault()?.Item2);
        }