void CopyFileToDocumentsDirectory(NSUrl fromUrl) { NSUrl toURL = DocumentsDirectory.Append(fromUrl.LastPathComponent, false); bool success = false; NSError error; NSFileCoordinator fileCoordinator = new NSFileCoordinator(); fileCoordinator.CoordinateWriteWrite(fromUrl, NSFileCoordinatorWritingOptions.ForMoving, toURL, NSFileCoordinatorWritingOptions.ForReplacing, out error, (src, dst) => { NSFileManager fileManager = new NSFileManager(); success = fileManager.Copy(src, dst, out error); if (success) { var attributes = new NSFileAttributes { FileExtensionHidden = true }; fileManager.SetAttributes(attributes, dst.Path); Console.WriteLine("Moved file: {0} to: {1}.", src.AbsoluteString, dst.AbsoluteString); } }); // In your app, handle this gracefully. if (!success) { Console.WriteLine("Couldn't move file: {0} to: {1}. Error: {3}.", fromUrl.AbsoluteString, toURL.AbsoluteString, error.Description); } }
private void DocumentPicker_DidPickDocument(object sender, UIDocumentPickedEventArgs e) { e.Url.StartAccessingSecurityScopedResource(); var doc = new UIDocument(e.Url); var fileName = doc.LocalizedName; if (string.IsNullOrWhiteSpace(fileName)) { var path = doc.FileUrl?.ToString(); if (path != null) { path = WebUtility.UrlDecode(path); var split = path.LastIndexOf('/'); fileName = path.Substring(split + 1); } } var fileCoordinator = new NSFileCoordinator(); NSError error; fileCoordinator.CoordinateRead(e.Url, NSFileCoordinatorReadingOptions.WithoutChanges, out error, (url) => { var data = NSData.FromUrl(url).ToArray(); SelectFileResult(data, fileName ?? "unknown_file_name"); }); e.Url.StopAccessingSecurityScopedResource(); }
public Task <IFile> CreateFile(string path, byte[] contents) { var tcs = new TaskCompletionSource <IFile> (); var f = new CloudFile(path, documentsUrl); if (contents != null) { var c = new NSFileCoordinator(filePresenterOrNil: (INSFilePresenter)null); NSError coordErr; c.CoordinateWrite(f.LocalUrl, NSFileCoordinatorWritingOptions.ForReplacing, out coordErr, newUrl => { using (var d = NSData.FromArray(contents)) { NSError error; if (d.Save(newUrl, false, out error)) { tcs.SetResult(f); } else { tcs.SetException(new CloudException("Failed to create new file", error)); } } }); if (coordErr != null) { tcs.TrySetException(new CloudException("Could not coordinate iCloud write for CreateFile", coordErr)); } } else { tcs.SetResult(f); } return(tcs.Task); }
void CopyFileToDocumentsDirectory(NSUrl fromUrl) { NSUrl toURL = DocumentsDirectory.Append (fromUrl.LastPathComponent, false); bool success = false; NSError error; NSFileCoordinator fileCoordinator = new NSFileCoordinator (); fileCoordinator.CoordinateWriteWrite (fromUrl, NSFileCoordinatorWritingOptions.ForMoving, toURL, NSFileCoordinatorWritingOptions.ForReplacing, out error, (src, dst) => { NSFileManager fileManager = new NSFileManager(); success = fileManager.Copy(src, dst, out error); if (success) { var attributes = new NSFileAttributes { ExtensionHidden = true }; fileManager.SetAttributes (attributes, dst.Path); Console.WriteLine ("Moved file: {0} to: {1}.", src.AbsoluteString, dst.AbsoluteString); } }); // In your app, handle this gracefully. if (!success) Console.WriteLine ("Couldn't move file: {0} to: {1}. Error: {3}.", fromUrl.AbsoluteString, toURL.AbsoluteString, error.Description); }
public Task <bool> Move(string fromPath, string toPath) { var tcs = new TaskCompletionSource <bool> (); var fromLocalPath = GetLocalPath(fromPath); var toLocalPath = GetLocalPath(toPath); var fromUrl = NSUrl.FromFilename(fromLocalPath); var toUrl = NSUrl.FromFilename(toLocalPath); Task.Run(() => { var c = new NSFileCoordinator(filePresenterOrNil: null); NSError coordErr; c.CoordinateReadWrite(fromUrl, NSFileCoordinatorReadingOptions.WithoutChanges, toUrl, NSFileCoordinatorWritingOptions.ForReplacing, out coordErr, (newFromUrl, newToUrl) => { try { var man = new NSFileManager(); NSError moveErr; var r = man.Move(newFromUrl, newToUrl, out moveErr); Debug.WriteLineIf(!r, moveErr); needsRefresh = true; tcs.SetResult(r); } catch (Exception ex) { Debug.WriteLine(ex); tcs.SetResult(false); } }); }); return(tcs.Task); }
public static Task<NSUrl> CopyToDocumentsDirectoryAsync(NSUrl fromUrl) { var tcs = new TaskCompletionSource<NSUrl>(); NSUrl localDocDir = GetDocumentDirectoryUrl (); NSUrl toURL = localDocDir.Append (fromUrl.LastPathComponent, false); bool success = false; NSError coordinationError, copyError = null; NSFileCoordinator fileCoordinator = new NSFileCoordinator (); ThreadPool.QueueUserWorkItem (_ => { fileCoordinator.CoordinateReadWrite (fromUrl, 0, toURL, NSFileCoordinatorWritingOptions.ForReplacing, out coordinationError, (src, dst) => { NSFileManager fileManager = new NSFileManager(); success = fileManager.Copy(src, dst, out copyError); if (success) { var attributes = new NSFileAttributes { ExtensionHidden = true }; fileManager.SetAttributes (attributes, dst.Path); Console.WriteLine ("Copied file: {0} to: {1}.", src.AbsoluteString, dst.AbsoluteString); } }); // In your app, handle this gracefully. if (!success) Console.WriteLine ("Couldn't copy file: {0} to: {1}. Error: {2}.", fromUrl.AbsoluteString, toURL.AbsoluteString, (coordinationError ?? copyError).Description); tcs.SetResult(toURL); }); return tcs.Task; }
public Task <bool> Move(string newPath) { var tcs = new TaskCompletionSource <bool> (); NSUrl newUrl = documentsUrl.Append(newPath, false); Task.Factory.StartNew(() => { var c = new NSFileCoordinator(filePresenterOrNil: null); NSError coordErr; c.CoordinateWriteWrite(LocalUrl, NSFileCoordinatorWritingOptions.ForMoving, newUrl, NSFileCoordinatorWritingOptions.ForReplacing, out coordErr, (url1, url2) => { bool r = false; using (var m = new NSFileManager()) { NSError remErr; r = m.Move(url1, url2, out remErr); if (r) { Path = newPath; LocalUrl = newUrl; LocalPath = LocalUrl.Path; } } tcs.SetResult(r); }); }); return(tcs.Task); }
public Task <bool> DeleteFile(string path) { var localUrl = documentsUrl.Append(path, false); var tcs = new TaskCompletionSource <bool> (); Task.Factory.StartNew(() => { var c = new NSFileCoordinator(filePresenterOrNil: null); NSError coordErr; c.CoordinateWrite(localUrl, NSFileCoordinatorWritingOptions.ForDeleting, out coordErr, newUrl => { bool r = false; using (var m = new NSFileManager()) { NSError remErr; r = m.Remove(newUrl, out remErr); } tcs.SetResult(r); }); if (coordErr != null) { tcs.SetResult(false); } }); return(tcs.Task); }
public Task <bool> CreateDirectory(string path) { var tcs = new TaskCompletionSource <bool> (); var localPath = GetLocalPath(path); var url = NSUrl.FromFilename(localPath); Task.Factory.StartNew(() => { var c = new NSFileCoordinator(filePresenterOrNil: null); NSError coordErr; c.CoordinateWrite(url, NSFileCoordinatorWritingOptions.ForReplacing, out coordErr, newUrl => { try { if (Directory.Exists(newUrl.Path)) { tcs.SetResult(true); return; } var man = new NSFileManager(); NSError mkdirErr; var r = man.CreateDirectory(newUrl, false, null, out mkdirErr); Debug.WriteLineIf(!r, mkdirErr); tcs.SetResult(r); } catch (Exception ex) { Debug.WriteLine(ex); tcs.SetResult(false); } }); }); return(tcs.Task); }
/// <summary> /// Moves a file from a given source url location to a given destination url. /// </summary> /// <returns><c>true</c>, if file was moved, <c>false</c> otherwise.</returns> /// <param name="fromURL">From UR.</param> /// <param name="toURL">To UR.</param> private bool MoveFile(string fromURL, string toURL) { bool successful = true; // Get source options var srcURL = NSUrl.FromFilename(fromURL); var srcIntent = NSFileAccessIntent.CreateReadingIntent(srcURL, NSFileCoordinatorReadingOptions.ForUploading); // Get destination options var dstURL = NSUrl.FromFilename(toURL); var dstIntent = NSFileAccessIntent.CreateReadingIntent(dstURL, NSFileCoordinatorReadingOptions.ForUploading); // Create an array var intents = new NSFileAccessIntent[] { srcIntent, dstIntent }; // Initialize a file coordination with intents var queue = new NSOperationQueue(); var fileCoordinator = new NSFileCoordinator(); fileCoordinator.CoordinateAccess(intents, queue, (err) => { // Was there an error? if (err != null) { // Yes, inform caller Console.WriteLine("Error: {0}", err.LocalizedDescription); successful = false; } }); // Return successful return(successful); }
/// <summary> /// Moves a file from a given source url location to a given destination url. /// </summary> /// <returns><c>true</c>, if file was moved, <c>false</c> otherwise.</returns> /// <param name="fromURL">From UR.</param> /// <param name="toURL">To UR.</param> private bool MoveFile(string fromURL, string toURL) { bool successful = true; // Get source options var srcURL = NSUrl.FromFilename (fromURL); var srcIntent = NSFileAccessIntent.CreateReadingIntent (srcURL, NSFileCoordinatorReadingOptions.ForUploading); // Get destination options var dstURL = NSUrl.FromFilename (toURL); var dstIntent = NSFileAccessIntent.CreateReadingIntent (dstURL, NSFileCoordinatorReadingOptions.ForUploading); // Create an array var intents = new NSFileAccessIntent[] { srcIntent, dstIntent }; // Initialize a file coordination with intents var queue = new NSOperationQueue (); var fileCoordinator = new NSFileCoordinator (); fileCoordinator.CoordinateAccess (intents, queue, (err) => { // Was there an error? if (err!=null) { // Yes, inform caller Console.WriteLine("Error: {0}",err.LocalizedDescription); successful = false; } }); // Return successful return successful; }
public Task <bool> CreateDirectory(string path) { var tcs = new TaskCompletionSource <bool> (); var localPath = GetLocalPath(path); var url = NSUrl.FromFilename(localPath); var c = new NSFileCoordinator(filePresenterOrNil: (INSFilePresenter)null); NSError coordErr; c.CoordinateWrite(url, NSFileCoordinatorWritingOptions.ForReplacing, out coordErr, newUrl => { try { var man = new NSFileManager(); NSError mkdirErr; var r = man.CreateDirectory(newUrl, true, null, out mkdirErr); Debug.WriteLineIf(!r, mkdirErr); tcs.SetResult(r); } catch (Exception ex) { Console.WriteLine(ex); tcs.SetResult(false); } }); if (coordErr != null) { Console.WriteLine(coordErr.DebugDescription); tcs.TrySetResult(false); } return(tcs.Task); }
void abreDocumento(object s, EventArgs e) { // Allow the Document picker to select a range of document types var allowedUTIs = new string[] { UTType.UTF8PlainText, UTType.PlainText, UTType.RTF, UTType.PNG, UTType.Text, UTType.PDF, UTType.Image }; // Display the picker //var picker = new UIDocumentPickerViewController (allowedUTIs, UIDocumentPickerMode.Open); var pickerMenu = new UIDocumentMenuViewController(allowedUTIs, UIDocumentPickerMode.Open); pickerMenu.DidPickDocumentPicker += (sender, args) => { // Wireup Document Picker args.DocumentPicker.DidPickDocument += (sndr, pArgs) => { // IMPORTANT! You must lock the security scope before you can // access this file var securityEnabled = pArgs.Url.StartAccessingSecurityScopedResource(); // Open the document funciones.MessageBox("Aviso", pArgs.Url.ToString()); // TODO: This should work but doesn't // Apple's WWDC 2014 sample project does this but it blows // up in Xamarin NSFileCoordinator fileCoordinator = new NSFileCoordinator(); NSError err; fileCoordinator.CoordinateRead(pArgs.Url, 0, out err, (NSUrl newUrl) => { NSData data = NSData.FromUrl(newUrl); Console.WriteLine("Data: {0}", data); }); // IMPORTANT! You must release the security lock established // above. pArgs.Url.StopAccessingSecurityScopedResource(); }; // Display the document picker PresentViewController(args.DocumentPicker, true, null); }; pickerMenu.ModalPresentationStyle = UIModalPresentationStyle.Popover; PresentViewController(pickerMenu, true, null); UIPopoverPresentationController presentationPopover = pickerMenu.PopoverPresentationController; if (presentationPopover != null) { presentationPopover.SourceView = this.View; presentationPopover.PermittedArrowDirections = UIPopoverArrowDirection.Down; presentationPopover.SourceRect = ((UIButton)s).Frame; } }
public void CoordinateRead_Null() { using (var url = GetUrl()) using (var fc = new NSFileCoordinator()) { NSError err; // NULL is not documented by Apple but it crash the app with: // NSFileCoordinator: A surprising server error was signaled. Details: Connection invalid Assert.Throws <ArgumentNullException> (() => fc.CoordinateRead(url, NSFileCoordinatorReadingOptions.WithoutChanges, out err, null)); } }
public void CoordinateWrite_Null() { using (var url = GetUrl()) using (var fc = new NSFileCoordinator()) { NSError err; // NULL is not documented by Apple but it crash the app with: // NSFileCoordinator: A surprising server error was signaled. Details: Connection invalid fc.CoordinateWrite(url, NSFileCoordinatorWritingOptions.ForDeleting, out err, null); } }
public void CoordinateBatch_Action() { using (var url = GetUrl()) using (var fc = new NSFileCoordinator()) { NSError err; fileop = false; fc.CoordinateBatc(new NSUrl[] { url }, NSFileCoordinatorReadingOptions.WithoutChanges, new NSUrl[] { url }, NSFileCoordinatorWritingOptions.ForDeleting, out err, Action); Assert.True(fileop, "fileop/sync"); Assert.Null(err, "NSError"); } }
public void CoordinateReadWrite() { using (var url = GetUrl()) using (var fc = new NSFileCoordinator()) { NSError err; fileop = false; fc.CoordinateReadWrite(url, NSFileCoordinatorReadingOptions.WithoutChanges, url, NSFileCoordinatorWritingOptions.ForDeleting, out err, FileOp); Assert.True(fileop, "fileop/sync"); Assert.Null(err, "NSError"); } }
public FileProvider() { NSError error; FileCoordinator = new NSFileCoordinator (); FileCoordinator.PurposeIdentifier = ProviderIdentifier; FileCoordinator.CoordinateWrite (DocumentStorageUrl, 0, out error, (newUrl) => { NSError err; // ensure that the DocumentStorageUrl actually exists NSFileManager.DefaultManager.CreateDirectory (newUrl, true, null, out err); }); }
public FileProvider() { NSError error; FileCoordinator = new NSFileCoordinator(); FileCoordinator.PurposeIdentifier = ProviderIdentifier; FileCoordinator.CoordinateWrite(DocumentStorageUrl, 0, out error, (newUrl) => { NSError err; // ensure that the DocumentStorageUrl actually exists NSFileManager.DefaultManager.CreateDirectory(newUrl, true, null, out err); }); }
public void CoordinateBatch_Action_Null() { using (var url = GetUrl()) using (var fc = new NSFileCoordinator()) { NSError err; // NULL is not documented by Apple but it crash the app with: // NSFileCoordinator: A surprising server error was signaled. Details: Connection invalid #if NET Assert.Throws <ArgumentNullException> (() => fc.CoordinateBatch(new NSUrl[] { url }, NSFileCoordinatorReadingOptions.WithoutChanges, new NSUrl[] { url }, NSFileCoordinatorWritingOptions.ForDeleting, out err, null)); #else Assert.Throws <ArgumentNullException> (() => fc.CoordinateBatc(new NSUrl[] { url }, NSFileCoordinatorReadingOptions.WithoutChanges, new NSUrl[] { url }, NSFileCoordinatorWritingOptions.ForDeleting, out err, null)); #endif } }
public void DeleteFileAtURL(NSUrl fileURL) { var fileCoordinator = new NSFileCoordinator (); NSError error; bool success = false; fileCoordinator.CoordinateWrite (fileURL, NSFileCoordinatorWritingOptions.ForDeleting, out error, writingURL => { NSFileManager fileManager = new NSFileManager(); success = fileManager.Remove(writingURL, out error); }); // In your app, handle this gracefully. if (!success) { string msg = string.Format("Couldn't delete file at URL {0}. Error: {1}.", fileURL.AbsoluteString, error.Description); throw new InvalidProgramException (msg); } }
public override async Task DeleteAsync(CancellationToken ct, StorageDeleteOption options) { var intent = NSFileAccessIntent.CreateWritingIntent(_nsUrl, NSFileCoordinatorWritingOptions.ForDeleting); using var coordinator = new NSFileCoordinator(); await coordinator.CoordinateAsync(new[] { intent }, new NSOperationQueue(), () => { using var _ = _nsUrl.BeginSecurityScopedAccess(); NSError deleteError; NSFileManager.DefaultManager.Remove(_nsUrl, out deleteError); if (deleteError != null) { throw new UnauthorizedAccessException($"Can't delete file. {deleteError}"); } }); }
public void DeleteFileAtURL(NSUrl fileURL) { var fileCoordinator = new NSFileCoordinator(); NSError error; bool success = false; fileCoordinator.CoordinateWrite(fileURL, NSFileCoordinatorWritingOptions.ForDeleting, out error, writingURL => { NSFileManager fileManager = new NSFileManager(); success = fileManager.Remove(writingURL, out error); }); // In your app, handle this gracefully. if (!success) { string msg = string.Format("Couldn't delete file at URL {0}. Error: {1}.", fileURL.AbsoluteString, error.Description); throw new InvalidProgramException(msg); } }
public Task <IFile> CreateFile(string path, byte[] contents) { var tcs = new TaskCompletionSource <IFile> (); var f = new CloudFile(path, documentsUrl); if (contents != null) { Task.Factory.StartNew(() => { var c = new NSFileCoordinator(filePresenterOrNil: null); NSError coordErr; c.CoordinateWrite(f.LocalUrl, NSFileCoordinatorWritingOptions.ForReplacing, out coordErr, newUrl => { var newPath = newUrl.Path; // Console.WriteLine ("CLOUD WRITE TO " + newUrl + " from: " + f.LocalUrl + " at: " + newPath); var dir = Path.GetDirectoryName(newPath); if (!string.IsNullOrEmpty(dir) && dir != "/" && !Directory.Exists(dir)) { Directory.CreateDirectory(dir); } try { File.WriteAllBytes(newPath, contents); tcs.SetResult(f); } catch (Exception ex) { tcs.SetException(ex); } }); if (coordErr != null) { tcs.SetException(new Exception("Could not coordinate iCloud write for CreateFile: " + coordErr.DebugDescription)); } }); } else { tcs.SetResult(f); } return(tcs.Task); }
void PrintFileContent(NSUrl url) { NSData data = null; NSError error = null; NSFileCoordinator fileCoordinator = new NSFileCoordinator(); fileCoordinator.CoordinateRead(url, (NSFileCoordinatorReadingOptions)0, out error, newUrl => { data = NSData.FromUrl(newUrl); }); if (error != null) { Console.WriteLine("CoordinateRead error {0}", error); } else { Console.WriteLine("File name: {0}", url.LastPathComponent); Console.WriteLine(data); } }
public Task <bool> Delete() { var tcs = new TaskCompletionSource <bool> (); var c = new NSFileCoordinator(filePresenterOrNil: (INSFilePresenter)null); NSError coordErr; c.CoordinateWrite(LocalUrl, NSFileCoordinatorWritingOptions.ForDeleting, out coordErr, newUrl => { bool r = false; using (var m = new NSFileManager()) { NSError remErr; r = m.Remove(newUrl, out remErr); } tcs.SetResult(r); }); if (coordErr != null) { tcs.TrySetResult(false); } return(tcs.Task); }
static Task <NSUrl> CopyToDocumentsDirectoryAsync(NSUrl fromUrl) { var tcs = new TaskCompletionSource <NSUrl>(); NSUrl localDocDir = GetDocumentDirectoryUrl(); NSUrl toURL = localDocDir.Append(fromUrl.LastPathComponent, false); bool success = false; NSError coordinationError, copyError = null; NSFileCoordinator fileCoordinator = new NSFileCoordinator(); ThreadPool.QueueUserWorkItem(_ => { fileCoordinator.CoordinateReadWrite(fromUrl, 0, toURL, NSFileCoordinatorWritingOptions.ForReplacing, out coordinationError, (src, dst) => { NSFileManager fileManager = new NSFileManager(); success = fileManager.Copy(src, dst, out copyError); if (success) { var attributes = new NSFileAttributes { FileExtensionHidden = true }; fileManager.SetAttributes(attributes, dst.Path); Console.WriteLine("Copied file: {0} to: {1}.", src.AbsoluteString, dst.AbsoluteString); } }); // In your app, handle this gracefully. if (!success) { Console.WriteLine("Couldn't copy file: {0} to: {1}. Error: {2}.", fromUrl.AbsoluteString, toURL.AbsoluteString, (coordinationError ?? copyError).Description); } tcs.SetResult(toURL); }); return(tcs.Task); }
public static async Task CoordinateAsync(this NSFileCoordinator coordinator, NSFileAccessIntent[] intents, NSOperationQueue queue, Action operation) { var completionSource = new TaskCompletionSource <bool>(); coordinator.CoordinateAccess(intents, queue, (error) => { try { if (error != null) { throw new UnauthorizedAccessException($"Could not coordinate file system operation. {error}"); } operation?.Invoke(); completionSource.TrySetResult(true); } catch (Exception ex) { completionSource.TrySetException(ex); } }); await completionSource.Task; }
public static async Task <FileResult[]> EnsurePhysicalFileResultsAsync(params NSUrl[] urls) { if (urls == null || urls.Length == 0) { return(Array.Empty <FileResult>()); } var opts = NSFileCoordinatorReadingOptions.WithoutChanges; var intents = urls.Select(x => NSFileAccessIntent.CreateReadingIntent(x, opts)).ToArray(); using var coordinator = new NSFileCoordinator(); var tcs = new TaskCompletionSource <FileResult[]>(); coordinator.CoordinateAccess(intents, new NSOperationQueue(), error => { if (error != null) { tcs.TrySetException(new NSErrorException(error)); return; } var bookmarks = new List <FileResult>(); foreach (var intent in intents) { var url = intent.Url; var result = new BookmarkDataFileResult(url); bookmarks.Add(result); } tcs.TrySetResult(bookmarks.ToArray()); }); return(await tcs.Task); }
public Task<IFile> CreateFile (string path, byte[] contents) { var tcs = new TaskCompletionSource<IFile> (); var f = new CloudFile (path, documentsUrl); if (contents != null) { Task.Factory.StartNew (() => { var c = new NSFileCoordinator (filePresenterOrNil: null); NSError coordErr; c.CoordinateWrite (f.LocalUrl, NSFileCoordinatorWritingOptions.ForReplacing, out coordErr, newUrl => { var newPath = newUrl.Path; // Console.WriteLine ("CLOUD WRITE TO " + newUrl + " from: " + f.LocalUrl + " at: " + newPath); var dir = Path.GetDirectoryName (newPath); if (!string.IsNullOrEmpty (dir) && dir != "/" && !Directory.Exists (dir)) { Directory.CreateDirectory (dir); } try { File.WriteAllBytes (newPath, contents); tcs.SetResult (f); } catch (Exception ex) { tcs.SetException (ex); } }); if (coordErr != null) { tcs.SetException (new Exception ("Could not coordinate iCloud write for CreateFile: " + coordErr.DebugDescription)); } }); } else { tcs.SetResult (f); } return tcs.Task; }
/// <summary> /// Views the did load. /// </summary> public override void ViewDidLoad () { base.ViewDidLoad (); // Save the default text area height _documentTextHeight = DocumentText.Frame.Height; // var picker = new UIDocumentPickerViewController (srcURL, UIDocumentPickerMode.ExportToService); // Watch for a new document being created ThisApp.DocumentLoaded += (document) => { // Display the contents of the document DocumentText.Text = document.Contents; // Watch for the document being modified by an outside source document.DocumentModified += (doc) => { // Display the updated contents of the document DocumentText.Text = doc.Contents; Console.WriteLine("Document contents have been updated"); }; }; // Wireup events for the text editor DocumentText.ShouldBeginEditing= delegate(UITextView field){ //Placeholder MoveDocumentText(_documentTextHeight-170f); return true; }; DocumentText.ShouldEndEditing= delegate (UITextView field){ MoveDocumentText(_documentTextHeight); ThisApp.Document.Contents = DocumentText.Text; return true; }; // Wireup the Save button SaveButton.Clicked += (sender, e) => { // Close the keyboard DocumentText.ResignFirstResponder(); // Save the changes to the document ThisApp.SaveDocument(); }; // Wireup the Action buttom ActionButton.Clicked += (s, e) => { // Allow the Document picker to select a range of document types var allowedUTIs = new string[] { UTType.UTF8PlainText, UTType.PlainText, UTType.RTF, UTType.PNG, UTType.Text, UTType.PDF, UTType.Image }; // Display the picker //var picker = new UIDocumentPickerViewController (allowedUTIs, UIDocumentPickerMode.Open); var pickerMenu = new UIDocumentMenuViewController(allowedUTIs, UIDocumentPickerMode.Open); pickerMenu.DidPickDocumentPicker += (sender, args) => { // Wireup Document Picker args.DocumentPicker.DidPickDocument += (sndr, pArgs) => { // IMPORTANT! You must lock the security scope before you can // access this file var securityEnabled = pArgs.Url.StartAccessingSecurityScopedResource(); // Open the document ThisApp.OpenDocument(pArgs.Url); // TODO: This should work but doesn't // Apple's WWDC 2014 sample project does this but it blows // up in Xamarin NSFileCoordinator fileCoordinator = new NSFileCoordinator(); NSError err; fileCoordinator.CoordinateRead (pArgs.Url, 0, out err, (NSUrl newUrl) => { NSData data = NSData.FromUrl(newUrl); Console.WriteLine("Data: {0}",data); }); // IMPORTANT! You must release the security lock established // above. pArgs.Url.StopAccessingSecurityScopedResource(); }; // Display the document picker PresentViewController(args.DocumentPicker,true,null); }; pickerMenu.ModalPresentationStyle = UIModalPresentationStyle.Popover; PresentViewController(pickerMenu,true,null); UIPopoverPresentationController presentationPopover = pickerMenu.PopoverPresentationController; if (presentationPopover!=null) { presentationPopover.SourceView = this.View; presentationPopover.PermittedArrowDirections = UIPopoverArrowDirection.Down; presentationPopover.SourceRect = ((UIButton)s).Frame; } }; }
public Task<bool> CreateDirectory (string path) { var tcs = new TaskCompletionSource<bool> (); var localPath = GetLocalPath (path); var url = NSUrl.FromFilename (localPath); Task.Factory.StartNew (() => { var c = new NSFileCoordinator (filePresenterOrNil: null); NSError coordErr; c.CoordinateWrite (url, NSFileCoordinatorWritingOptions.ForReplacing, out coordErr, newUrl => { try { if (Directory.Exists (newUrl.Path)) { tcs.SetResult (true); return; } var man = new NSFileManager (); NSError mkdirErr; var r = man.CreateDirectory (newUrl, false, null, out mkdirErr); Debug.WriteLineIf (!r, mkdirErr); tcs.SetResult (r); } catch (Exception ex) { Debug.WriteLine (ex); tcs.SetResult (false); } }); }); return tcs.Task; }
public Task<bool> Move (string fromPath, string toPath) { var tcs = new TaskCompletionSource<bool> (); var fromLocalPath = GetLocalPath (fromPath); var toLocalPath = GetLocalPath (toPath); var fromUrl = NSUrl.FromFilename (fromLocalPath); var toUrl = NSUrl.FromFilename (toLocalPath); Task.Run (() => { var c = new NSFileCoordinator (filePresenterOrNil: null); NSError coordErr; c.CoordinateReadWrite (fromUrl, NSFileCoordinatorReadingOptions.WithoutChanges, toUrl, NSFileCoordinatorWritingOptions.ForReplacing, out coordErr, (newFromUrl, newToUrl) => { try { var man = new NSFileManager (); NSError moveErr; var r = man.Move (newFromUrl, newToUrl, out moveErr); Debug.WriteLineIf (!r, moveErr); needsRefresh = true; tcs.SetResult (r); } catch (Exception ex) { Debug.WriteLine (ex); tcs.SetResult (false); } }); }); return tcs.Task; }
public Task<bool> Delete () { var tcs = new TaskCompletionSource<bool> (); Task.Factory.StartNew (() => { var c = new NSFileCoordinator (filePresenterOrNil: null); NSError coordErr; c.CoordinateWrite (LocalUrl, NSFileCoordinatorWritingOptions.ForDeleting, out coordErr, newUrl => { bool r = false; using (var m = new NSFileManager ()) { NSError remErr; r = m.Remove (newUrl, out remErr); } tcs.SetResult (r); }); }); return tcs.Task; }
public Task<bool> Move (string newPath) { var tcs = new TaskCompletionSource<bool> (); NSUrl newUrl = documentsUrl.Append (newPath, false); Task.Factory.StartNew (() => { var c = new NSFileCoordinator (filePresenterOrNil: null); NSError coordErr; c.CoordinateWriteWrite (LocalUrl, NSFileCoordinatorWritingOptions.ForMoving, newUrl, NSFileCoordinatorWritingOptions.ForReplacing, out coordErr, (url1, url2) => { bool r = false; using (var m = new NSFileManager ()) { NSError remErr; r = m.Move (url1, url2, out remErr); if (r) { Path = newPath; LocalUrl = newUrl; LocalPath = LocalUrl.Path; } } tcs.SetResult (r); }); }); return tcs.Task; }
void PrintFileContent(NSUrl url) { NSData data = null; NSError error = null; NSFileCoordinator fileCoordinator = new NSFileCoordinator (); fileCoordinator.CoordinateRead (url, (NSFileCoordinatorReadingOptions)0, out error, newUrl => { data = NSData.FromUrl(newUrl); }); if (error != null) { Console.WriteLine ("CoordinateRead error {0}", error); } else { Console.WriteLine ("File name: {0}", url.LastPathComponent); Console.WriteLine (data); } }
/// <summary> /// Views the did load. /// </summary> public override void ViewDidLoad() { base.ViewDidLoad(); // Save the default text area height _documentTextHeight = DocumentText.Frame.Height; // var picker = new UIDocumentPickerViewController (srcURL, UIDocumentPickerMode.ExportToService); // Watch for a new document being created ThisApp.DocumentLoaded += (document) => { // Display the contents of the document DocumentText.Text = document.Contents; // Watch for the document being modified by an outside source document.DocumentModified += (doc) => { // Display the updated contents of the document DocumentText.Text = doc.Contents; Console.WriteLine("Document contents have been updated"); }; }; // Wireup events for the text editor DocumentText.ShouldBeginEditing = delegate(UITextView field){ //Placeholder MoveDocumentText(_documentTextHeight - 170f); return(true); }; DocumentText.ShouldEndEditing = delegate(UITextView field){ MoveDocumentText(_documentTextHeight); ThisApp.Document.Contents = DocumentText.Text; return(true); }; // Wireup the Save button SaveButton.Clicked += (sender, e) => { // Close the keyboard DocumentText.ResignFirstResponder(); // Save the changes to the document ThisApp.SaveDocument(); }; // Wireup the Action buttom ActionButton.Clicked += (s, e) => { // Allow the Document picker to select a range of document types var allowedUTIs = new string[] { UTType.UTF8PlainText, UTType.PlainText, UTType.RTF, UTType.PNG, UTType.Text, UTType.PDF, UTType.Image }; // Display the picker //var picker = new UIDocumentPickerViewController (allowedUTIs, UIDocumentPickerMode.Open); var pickerMenu = new UIDocumentMenuViewController(allowedUTIs, UIDocumentPickerMode.Open); pickerMenu.DidPickDocumentPicker += (sender, args) => { // Wireup Document Picker args.DocumentPicker.DidPickDocument += (sndr, pArgs) => { // IMPORTANT! You must lock the security scope before you can // access this file var securityEnabled = pArgs.Url.StartAccessingSecurityScopedResource(); // Open the document ThisApp.OpenDocument(pArgs.Url); // TODO: This should work but doesn't // Apple's WWDC 2014 sample project does this but it blows // up in Xamarin NSFileCoordinator fileCoordinator = new NSFileCoordinator(); NSError err; fileCoordinator.CoordinateRead(pArgs.Url, 0, out err, (NSUrl newUrl) => { NSData data = NSData.FromUrl(newUrl); Console.WriteLine("Data: {0}", data); }); // IMPORTANT! You must release the security lock established // above. pArgs.Url.StopAccessingSecurityScopedResource(); }; // Display the document picker PresentViewController(args.DocumentPicker, true, null); }; pickerMenu.ModalPresentationStyle = UIModalPresentationStyle.Popover; PresentViewController(pickerMenu, true, null); UIPopoverPresentationController presentationPopover = pickerMenu.PopoverPresentationController; if (presentationPopover != null) { presentationPopover.SourceView = this.View; presentationPopover.PermittedArrowDirections = UIPopoverArrowDirection.Down; presentationPopover.SourceRect = ((UIButton)s).Frame; } }; }