public Task <OperationResult <string> > SaveVideo(string videoPath) { var tcs = new TaskCompletionSource <OperationResult <string> >(); if (string.IsNullOrEmpty(videoPath) || !File.Exists(videoPath)) { tcs.SetResult(OperationResult <string> .AsFailure("Invalid video file path specified")); return(tcs.Task); } var url = NSUrl.CreateFileUrl(videoPath, false, null); string localId = string.Empty; PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() => { var request = PHAssetChangeRequest.FromVideo(url); localId = request?.PlaceholderForCreatedAsset?.LocalIdentifier; }, (bool success, NSError error) => { if (!success && error != null) { tcs.SetResult(OperationResult <string> .AsFailure(error.LocalizedDescription)); } else { tcs.SetResult(OperationResult <string> .AsSuccess(localId)); } }); return(tcs.Task); }
public override void DidRequestDocumentCreation(UIDocumentBrowserViewController controller, Action <NSUrl, UIDocumentBrowserImportMode> importHandler) { var editController = new FileNameInputViewController(_extensions); void OnEditControllerOnOnViewDidDisappear(object sender, EventArgs args) { editController.OnViewDidDisappear -= OnEditControllerOnOnViewDidDisappear; if (string.IsNullOrEmpty(editController.FileName)) { importHandler(null, UIDocumentBrowserImportMode.None); return; } var documentFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); var tempFileName = editController.FileName; var path = Path.Combine(documentFolder, tempFileName); var tempFile = File.Create(path); tempFile.Dispose(); importHandler(NSUrl.CreateFileUrl(path, false, null), UIDocumentBrowserImportMode.Move); } editController.OnViewDidDisappear += OnEditControllerOnOnViewDidDisappear; controller.PresentViewController(editController, true, null); }
public OperationResult <Stream> GetFirstVideoFrame(string filePath) { var url = NSUrl.CreateFileUrl(filePath, false, null); var asset = new AVUrlAsset(url); var imageGenerator = new AVAssetImageGenerator(asset); imageGenerator.AppliesPreferredTrackTransform = true; CMTime actualTime; NSError error; var cgImage = imageGenerator.CopyCGImageAtTime(new CMTime(0, 1), out actualTime, out error); if (error != null) { return(OperationResult <Stream> .AsFailure(error.ToString())); } if (cgImage != null) { return(OperationResult <Stream> .AsSuccess(new UIImage(cgImage).AsJPEG().AsStream())); } else { return(OperationResult <Stream> .AsFailure("Image generation failed")); } }
public NSUrl moveItemToDocumentsDirectory(string fileName, string fileExtension) { NSFileManager fileManager = NSFileManager.DefaultManager; string[] dataPath = new string[] { applicationDocumentsDirectory() + "/" + fileName + "." + fileExtension }; NSUrl fileURLPrivate = NSBundle.MainBundle.GetUrlForResource(fileName, fileExtension); if (fileManager.FileExists(fileURLPrivate.Path)) { //First run, if file is not copied then copy, else return the path if already copied if (fileManager.FileExists(dataPath[0]) == false) { fileManager.Copy(fileURLPrivate.Path, dataPath[0], out NSError error); if (error == null) { return(NSUrl.CreateFileUrl(dataPath)); } else { Console.WriteLine("AWXamarin Error occured while copying"); } } else { return(NSUrl.CreateFileUrl(dataPath)); } Console.WriteLine("AWXamarin fileURLPrivate doesnt exist"); return(null); } return(null); }
private static Task <bool> HandleSettingsUriAsync(Uri uri) { var settingsString = uri.AbsolutePath.ToLowerInvariant(); //get exact match first _settingsHandlers.Value.TryGetValue(settingsString, out var launchAction); if (string.IsNullOrEmpty(launchAction)) { var secondaryMatch = _settingsHandlers.Value .Where(handler => settingsString.StartsWith(handler.Key, StringComparison.InvariantCultureIgnoreCase)) .Select(handler => handler.Value) .FirstOrDefault(); launchAction = secondaryMatch; } NSUrl url; if (string.IsNullOrEmpty(launchAction)) { url = NSUrl.CreateFileUrl(new string[] { "/System/Applications/System Preferences.app" }); } else { url = NSUrl.CreateFileUrl(new string[] { $@"/System/Library/PreferencePanes/{launchAction}.prefPane" }); } NSWorkspace.SharedWorkspace.OpenUrl(url); return(Task.FromResult(true)); }
ImageSource IVideoUtils.GetVideoThumbnail(string url) { NSUrl videoUrl = NSUrl.CreateFileUrl(url, null); var asset = AVAsset.FromUrl(videoUrl); var imageGenerator = AVAssetImageGenerator.FromAsset(asset); imageGenerator.AppliesPreferredTrackTransform = true; var seconds = asset.Duration.Seconds; CoreMedia.CMTime actualTime; CoreMedia.CMTime cmTime = asset.Duration; var timeScale = asset.Duration.TimeScale; cmTime.Value = (seconds > 5) ? timeScale * 5 : timeScale * 1; NSError error; var imageRef = imageGenerator.CopyCGImageAtTime(cmTime, out actualTime, out error); if (imageRef == null) { return(null); } var uiImage = UIImage.FromImage(imageRef); var img = Xamarin.Forms.ImageSource.FromStream(() => ((uiImage.AsPNG().AsStream()))); return(img); }
//needed for sharing to Facebook public Task <OperationResult <string> > LegacySaveVideo(string videoPath) { var tcs = new TaskCompletionSource <OperationResult <string> >(); if (string.IsNullOrEmpty(videoPath) || !File.Exists(videoPath)) { tcs.SetResult(OperationResult <string> .AsFailure("Invalid video file path specified")); return(tcs.Task); } var url = NSUrl.CreateFileUrl(videoPath, false, null); var library = new ALAssetsLibrary(); library.WriteVideoToSavedPhotosAlbum(url, (resultUrl, error) => { if (error == null) { tcs.SetResult(OperationResult <string> .AsSuccess(resultUrl.AbsoluteString)); } else { tcs.SetResult(OperationResult <string> .AsFailure(error.LocalizedDescription)); } }); return(tcs.Task); }
private static NSUrl DecodeUri(Uri uri) { if (!uri.IsAbsoluteUri || uri.Scheme == "") { uri = new Uri(MsAppXScheme + ":///" + uri.OriginalString.TrimStart(new char[] { '/' })); } var isResource = uri.Scheme.Equals(MsAppXScheme, StringComparison.OrdinalIgnoreCase) || uri.Scheme.Equals(MsAppDataScheme, StringComparison.OrdinalIgnoreCase); if (isResource) { var file = uri.PathAndQuery.TrimStart(new[] { '/' }); var fileName = Path.GetFileNameWithoutExtension(file); var fileExtension = Path.GetExtension(file)?.Replace(".", ""); return(NSBundle.MainBundle.GetUrlForResource(fileName, fileExtension)); } if (uri.IsFile) { return(NSUrl.CreateFileUrl(uri.PathAndQuery, relativeToUrl: null)); } return(new NSUrl(uri.ToString())); }
private static NSUrl DecodeUri(Uri uri) { if (!uri.IsAbsoluteUri || uri.Scheme == "") { uri = new Uri(MsAppXScheme + ":///" + uri.OriginalString.TrimStart(new char[] { '/' })); } if (uri.IsLocalResource()) { var file = uri.PathAndQuery.TrimStart(new[] { '/' }); var fileName = Path.GetFileNameWithoutExtension(file); var fileExtension = Path.GetExtension(file)?.Replace(".", ""); return(NSBundle.MainBundle.GetUrlForResource(fileName, fileExtension)); } if (uri.IsAppData()) { var filePath = AppDataUriEvaluator.ToPath(uri); return(NSUrl.CreateFileUrl(filePath, relativeToUrl: null)); } if (uri.IsFile) { return(NSUrl.CreateFileUrl(uri.PathAndQuery, relativeToUrl: null)); } return(new NSUrl(uri.ToString())); }
public OperationResult <double> GetVideoDuration(string filePath) { var url = NSUrl.CreateFileUrl(filePath, false, null); var asset = AVAsset.FromUrl(url); return(OperationResult <double> .AsSuccess(asset.Duration.Seconds)); }
/// <summary> /// Displays the given text string as final output to the user using a <c>WebKit</c> view. /// </summary> /// <param name="text">The formatted text to display.</param> public void DisplayPreview(string text, string filePath) { // Are we already performing an update? if (Updating) { return; } // Save current scroll position Scroll = WebPreview.MainFrame.FrameView.DocumentView.EnclosingScrollView; if (Scroll != null) { VisibleRect = Scroll.ContentView.DocumentVisibleRect(); } // Update view contents Updating = true; WebPreview.Hidden = true; if (filePath == "") { WebPreview.MainFrame.LoadHtmlString(text, null); } else { var url = NSUrl.CreateFileUrl(filePath, true, null); WebPreview.MainFrame.LoadHtmlString(text, url); } }
public HashSet <TagViewModel> GetTags(string filePath) { var tags = new HashSet <TagViewModel> (); var url = NSUrl.CreateFileUrl(new string[] { filePath }); NSError error; var values = url.GetResourceValues(new NSString[] { new NSString("NSURLTagNamesKey") }, out error); foreach (var val in values) { var tagArray = val.Value as NSArray; if (tagArray == null) { continue; } for (nuint i = 0; i < tagArray.Count; i++) { tags.Add(new TagViewModel { Name = tagArray.GetItem <NSString>(i).ToString() }); } } return(tags); }
public void LoadFromPath(string filePath) { if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath)) { var url = NSUrl.CreateFileUrl(filePath, false, null); LoadFromAsset(AVAsset.FromUrl(url)); } }
private static NSUrl GetLocalFilePath() { var cache = NSSearchPath.GetDirectories(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomain.User); var cachedFolder = cache[0]; var fileName = Guid.NewGuid() + ".png"; var cachedFile = cachedFolder + fileName; return(NSUrl.CreateFileUrl(cachedFile, false, null)); }
private static UNNotificationAttachment CreateImageAttachment(UNNotificationRequest request) { var filePath = DownloadAttachedImageFile(request); var options = new UNNotificationAttachmentOptions(); var fileUrl = NSUrl.CreateFileUrl(filePath, false, null); var attachment = UNNotificationAttachment.FromIdentifier("image", fileUrl, options, out var error); return(error == null ? attachment : throw new Exception(error.LocalizedDescription)); }
protected override async Task <HttpTransfer> CreateUpload(HttpTransferRequest request) { if (request.HttpMethod != System.Net.Http.HttpMethod.Post && request.HttpMethod != System.Net.Http.HttpMethod.Put) { throw new ArgumentException($"Invalid Upload HTTP Verb {request.HttpMethod} - only PUT or POST are valid"); } var boundary = Guid.NewGuid().ToString("N"); var native = request.ToNative(); native["Content-Type"] = $"multipart/form-data; boundary={boundary}"; var tempPath = platform.GetUploadTempFilePath(request); this.logger.LogInformation("Writing temp form data body to " + tempPath); using (var fs = new FileStream(tempPath, FileMode.Create)) { if (!request.PostData.IsEmpty()) { fs.Write("--" + boundary); fs.Write($"Content-Type: text/plain; charset=utf-8"); fs.Write("Content-Disposition: form-data;"); fs.WriteLine(); fs.Write(request.PostData !); fs.WriteLine(); } } using (var fs = new FileStream(tempPath, FileMode.Append)) { using (var uploadFile = request.LocalFile.OpenRead()) { fs.Write("--" + boundary); fs.Write($"Content-Type: application/octet-stream"); fs.Write($"Content-Disposition: form-data; name=\"blob\"; filename=\"{request.LocalFile.Name}\""); fs.WriteLine(); await uploadFile.CopyToAsync(fs); fs.WriteLine(); fs.Write($"--{boundary}--"); } } this.logger.LogInformation("Form body written"); var tempFileUrl = NSUrl.CreateFileUrl(tempPath, null); var task = this.Session.CreateUploadTask(native, tempFileUrl); var taskId = TaskIdentifier.Create(request.LocalFile); task.TaskDescription = taskId.ToString(); var transfer = task.FromNative(); task.Resume(); return(transfer); }
public string ReadFile(string path, string userIdentity) { string result = String.Empty; if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0)) { if (FileExists(path)) { NSFileHandle fileHandle = null; NSError error = null; Exception exception = null; try { UIApplication.SharedApplication.InvokeOnMainThread(() => { _fileProtectionManagerService.DecryptFile(path); fileHandle = NSFileHandle.OpenReadUrl(NSUrl.CreateFileUrl(new[] { path }), out error); if (fileHandle != null) { var nsStringResult = NSString.FromData(fileHandle.ReadDataToEndOfFile(), NSStringEncoding.UTF8); if (nsStringResult != null) { result = nsStringResult.ToString(); } } _fileProtectionManagerService.EncryptFile(path, userIdentity); }); } catch (Exception ex) { exception = ex; } finally { if (fileHandle != null) { fileHandle.CloseFile(); } } if (error != null) { _loggingService.LogError(typeof(FileSystemService), new Exception(error.DebugDescription), error.Description); throw new NSErrorException(error); } else if (exception != null) { _loggingService.LogError(typeof(FileSystemService), exception, exception.Message); throw exception; } } } return(result); }
NSUrl localFilePath(string id) { var relPath = SettingsStudio.Settings.StringForKey(id); if (!string.IsNullOrEmpty(relPath)) { return(NSUrl.CreateFileUrl(new string [] { NSHomeDirectoryNative() }).Append(relPath, false)); } return(null); }
private void SetKML() { var bundle = NSBundle.MainBundle; var path = bundle.PathForResource("KML_Sample", "kml"); var url = NSUrl.CreateFileUrl(path, null); var parser = new GMUKMLParser(url); parser.Parse(); var renderer = new GMUGeometryRenderer(mapView, parser.Placemarks, parser.Styles); renderer.Render(); }
public override void ViewDidLoad() { base.ViewDidLoad(); var path = NSBundle.PathForResourceAbsolute("GeoJSON_Sample", "geojson", NibBundle.BundlePath); var url = NSUrl.CreateFileUrl(path, null); var jsonParser = new GMUGeoJSONParser(url); jsonParser.Parse(); var renderer = new GMUGeometryRenderer(mapView, jsonParser.Features); renderer.Render(); }
private void PlatformDeleteFile(string path) { if (FileExists(path)) { NSFileManager.DefaultManager.Remove(NSUrl.CreateFileUrl(new[] { path }), out NSError error); if (error != null) { throw new NSErrorException(error); } } }
public void OpenActionSheet(string path) { var window = UIApplication.SharedApplication.KeyWindow; var subviews = window.Subviews; var view = subviews.Last(); NSUrl videoUrl = NSUrl.CreateFileUrl(path, null); UIDocumentInteractionController openInWindow = UIDocumentInteractionController.FromUrl(videoUrl); openInWindow.PresentOptionsMenu(CGRect.Empty, view, true); //openInWindow.PresentOpenInMenu(CGRect.Empty, view, true); }
/// <summary> /// /// </summary> /// <param name="notificationImage"></param> /// <returns></returns> protected virtual async Task <UNNotificationAttachment> GetNativeImage(NotificationImage notificationImage) { if (notificationImage is null || notificationImage.HasValue == false) { return(null); } NSUrl imageAttachment = null; if (string.IsNullOrWhiteSpace(notificationImage.ResourceName) == false) { imageAttachment = NSBundle.MainBundle.GetUrlForResource(Path.GetFileNameWithoutExtension(notificationImage.ResourceName), Path.GetExtension(notificationImage.ResourceName)); } if (string.IsNullOrWhiteSpace(notificationImage.FilePath) == false) { if (File.Exists(notificationImage.FilePath)) { imageAttachment = NSUrl.CreateFileUrl(notificationImage.FilePath, false, null); } } if (notificationImage.Binary != null && notificationImage.Binary.Length > 0) { using (var stream = new MemoryStream(notificationImage.Binary)) { var image = Image.FromStream(stream); var imageExtension = image.RawFormat.ToString(); var cache = NSSearchPath.GetDirectories(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomain.User); var cachesFolder = cache[0]; var cacheFile = $"{cachesFolder}{NSProcessInfo.ProcessInfo.GloballyUniqueString}.{imageExtension}"; if (File.Exists(cacheFile)) { File.Delete(cacheFile); } await File.WriteAllBytesAsync(cacheFile, notificationImage.Binary); imageAttachment = NSUrl.CreateFileUrl(cacheFile, false, null); } } if (imageAttachment is null) { return(null); } var options = new UNNotificationAttachmentOptions(); return(UNNotificationAttachment.FromIdentifier("image", imageAttachment, options, out _)); }
void HandleVideo(MediaFile file) { if (file == null) { return; } var mediaUrl = file.Path; var documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal); var outputFile = Path.Combine(documentsDirectory, Guid.NewGuid().ToString() + ".mp4"); AVUrlAsset asset = new AVUrlAsset(NSUrl.CreateFileUrl(new string[] { mediaUrl })); AVAssetExportSession exportSession = new AVAssetExportSession(asset, AVAssetExportSession.Preset1280x720); var fileUrl = NSUrl.CreateFileUrl(new string[] { outputFile }); exportSession.OutputUrl = NSUrl.CreateFileUrl(new string[] { outputFile }); exportSession.OutputFileType = AVFileType.Mpeg4; LoadingScreen.Show(); LoadingScreen.SetText("Converting"); exportSession.ExportAsynchronously(() => { InvokeOnMainThread(() => { if (exportSession.Error != null) { int i = 3; } AVUrlAsset asset2 = new AVUrlAsset(NSUrl.CreateFileUrl(new string[] { mediaUrl })); AVAssetImageGenerator generator = new AVAssetImageGenerator(asset2); generator.AppliesPreferredTrackTransform = true; var thumbTime = new CMTime(0, 30); NSValue[] vals = new NSValue[] { NSValue.FromCMTime(thumbTime) }; CGSize maxSize = new CGSize(800, 600); //generator.MaximumSize = maxSize; generator.GenerateCGImagesAsynchronously(vals, (requestedTime, imageRef, actualTime, result, error) => { var previewImage = System.IO.Path.Combine(documentsDirectory, Guid.NewGuid() + ".jpg"); NSError err; UIImage.FromImage(new CGImage(imageRef)).AsJPEG(.75f).Save(previewImage, false, out err); InvokeOnMainThread(() => { LoadingScreen.Hide(); VideoPicked?.Invoke(outputFile, previewImage); }); }); }); }); }
private void Play() { if (string.IsNullOrEmpty(MediaUrl)) { LoadingSpinner.Hidden = true; return; } //f4v is not supported on iOS (thanks Apple) if (MediaUrl.EndsWith(".f4v", StringComparison.CurrentCultureIgnoreCase)) { //Show alert LoadingSpinner.Hidden = true; _dialog.Show(Translation.alert_display_failed_title, Translation.alert_display_failed_body, Translation.general_close, async() => { await ViewModel?.CloseCommand?.ExecuteAsync(); }); return; } if (MediaUrl.EndsWith(".mp4", StringComparison.CurrentCultureIgnoreCase) || MediaUrl.EndsWith(".m4v", StringComparison.CurrentCultureIgnoreCase)) { ImageView.Hidden = true; NSUrl url = NSUrl.CreateFileUrl(MediaUrl, null); AVPlayerItem item = new AVPlayerItem(url); _avLooper = new AVPlayerLooper(_avplayer, item, CoreMedia.CMTimeRange.InvalidRange); _avplayer.ReplaceCurrentItemWithPlayerItem(item); _avplayer.Play(); } else if (MediaUrl.EndsWith(".png", StringComparison.CurrentCultureIgnoreCase)) { _avplayer.Dispose(); _avplayer = null; _avplayerController.RemoveFromParentViewController(); _avplayerController.View.RemoveFromSuperview(); _avplayerController.Dispose(); _avplayerController = null; UIImage image = UIImage.FromFile(MediaUrl); ImageView.Image = image; } LoadingSpinner.Hidden = true; }
public void CapturePhoto(LivePhotoMode livePhotoMode, bool saveToPhotoLibrary) { _sessionQueue.DispatchAsync(() => { var photoSettings = AVCapturePhotoSettings.Create(); if (_photoOutput.SupportedFlashModes.Contains(NSNumber.FromInt32((int)AVCaptureFlashMode.Auto))) { photoSettings.FlashMode = AVCaptureFlashMode.Auto; } photoSettings.IsHighResolutionPhotoEnabled = true; var availablePhotoCodecTypes = photoSettings.AvailableEmbeddedThumbnailPhotoCodecTypes; if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0) && availablePhotoCodecTypes.Length > 0) { photoSettings.EmbeddedThumbnailPhotoFormat = new NSMutableDictionary { { AVVideo.CodecKey, availablePhotoCodecTypes[0].GetConstant() } }; } if (livePhotoMode == LivePhotoMode.On) { if (_presetConfiguration == SessionPresetConfiguration.LivePhotos && _photoOutput.IsLivePhotoCaptureSupported) { photoSettings.LivePhotoMovieFileUrl = NSUrl.CreateFileUrl(new[] { Path.GetTempPath(), $"{Guid.NewGuid()}.mov" }); } else { Console.WriteLine( "capture session: warning - trying to capture live photo but it's not supported by current configuration, capturing regular photo instead"); } } // Use a separate object for the photo capture delegate to isolate each capture life cycle. var photoCaptureDelegate = new PhotoCaptureDelegate(photoSettings, () => WillCapturePhotoAnimationAction(photoSettings), CapturingLivePhotoAction, CapturingCompletedAction) { ShouldSavePhotoToLibrary = saveToPhotoLibrary }; _photoOutput.CapturePhoto(photoSettings, photoCaptureDelegate); }); }
public Orientation GetVideoOrientation(string filePath) { var url = NSUrl.CreateFileUrl(filePath, false, null); var asset = AVAsset.FromUrl(url); var tracks = asset.TracksWithMediaType(AVMediaType.Video); if (tracks.Length == 0) { return(Orientation.Unknown); } var track = tracks[0]; return(GetVideoOrientation(track.PreferredTransform)); }
public HashSet <TagViewModel> AddOrUpdateTags(string filePath, HashSet <TagViewModel> tags) { tags.UnionWith(this.GetTags(filePath)); var tagListStrings = tags.SelectMany(x => x.Name).Distinct(); var url = NSUrl.CreateFileUrl(new string[] { filePath }); var tagList = new NSMutableArray(); foreach (var tag in tagListStrings) { tagList.Add(new NSString(tag)); } url.SetResource(new NSString("NSURLTagNamesKey"), tagList); return(tags); }
static public FormsCAKeyFrameAnimation CreateAnimationFromFileImageSource(FileImageSource imageSource) { FormsCAKeyFrameAnimation animation = null; string file = imageSource?.File; if (!string.IsNullOrEmpty(file)) { using (var parsedImageSource = CGImageSource.FromUrl(NSUrl.CreateFileUrl(file, null))) { animation = ImageAnimationHelper.CreateAnimationFromCGImageSource(parsedImageSource); } } return(animation); }
public override void LoadView() { var camera = CameraPosition.FromCamera(latitude: -28, longitude: 137, 4); mapView = MapView.FromCamera(frame: CGRect.Empty, camera: camera); this.View = mapView; var path = NSBundle.PathForResourceAbsolute("GeoJSON_sample", "json", NibBundle.BundlePath); var url = NSUrl.CreateFileUrl(path, null); geoJsonParser = new GMUGeoJSONParser(url); geoJsonParser.Parse(); renderer = new GMUGeometryRenderer(map: mapView, geometries: geoJsonParser.Features); renderer.Render(); }