static Task MoveToiCloud(NSUrl sourceUrl, NSUrl destinationURL) { if (NSFileManager.DefaultManager.UbiquityIdentityToken == null) { return(Task.FromResult <NSUrl> (null)); } var tcs = new TaskCompletionSource <object>(); // Upload the file to iCloud on a background queue. ThreadPool.QueueUserWorkItem(_ => { NSError error; NSFileManager fileManager = new NSFileManager(); bool success = fileManager.SetUbiquitous(true, sourceUrl, destinationURL, out error); if (!success) { Console.WriteLine(error); } tcs.SetResult(null); }); return(tcs.Task); }
public void GetSkipBackupAttribute() { Assert.False(NSFileManager.GetSkipBackupAttribute(NSBundle.MainBundle.ExecutableUrl.ToString()), "MainBundle"); string filename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), $"DoNotBackupMe-NSFileManager-{Process.GetCurrentProcess ().Id}"); try { File.WriteAllText(filename, "not worth a bit"); Assert.False(NSFileManager.GetSkipBackupAttribute(filename), "DoNotBackupMe-0"); NSFileManager.SetSkipBackupAttribute(filename, true); NSError error; Assert.True(NSFileManager.GetSkipBackupAttribute(filename, out error), "DoNotBackupMe-1"); Assert.Null(error, "error-1"); error = NSFileManager.SetSkipBackupAttribute(filename, false); Assert.False(NSFileManager.GetSkipBackupAttribute(filename), "DoNotBackupMe-2"); Assert.Null(error, "error-2"); } finally { // otherwise the attribute won't reset even if the file is overwritten File.Delete(filename); } }
/// <summary> /// Alls the inbox files. /// </summary> /// <returns></returns> public List <UPInboxFile> AllInboxFiles() { List <UPInboxFile> files = new List <UPInboxFile>(); #if PORTING Exception error; List <string> pathNames = NSFileManager.DefaultManager().ContentsOfDirectoryAtPathError(this.InboxPath, error); if (error) { if (error.Code() == NSFileReadNoSuchFileError) { DDLogInfo("Inbox directory %@ does not exist.", this.InboxPath); } else { DDLogError("Could not load files from inbox: %@", error); } } foreach (string path in pathNames) { UPInboxFile file = new UPInboxFile(this.InboxPath.StringByAppendingPathComponent(path), NSURL.FileURLWithPathIsDirectory(this.InboxPath.StringByAppendingPathComponent(path), false)); files.Add(file); } #endif return(files); }
partial void WKInterfaceButton5_Activated(WatchKit.WKInterfaceButton sender) { if (entryMode) { Console.WriteLine("EntryMode=true"); // Straight to dictation (no suggestions) // PresentTextInputController(new string[0], WatchKit.WKTextInputMode.Plain, (a) => { // Console.WriteLine("Dictation was accepted"); // if (a != null && a.Count > 0) { // enteredText = a.GetItem<NSObject>(0).ToString(); // Console.WriteLine(" " + a.GetItem<NSObject>(0)); // Name.SetText (a.GetItem<NSObject>(0).ToString()); // entryMode = false; // EnterText.SetTitle ("Save"); // } else { // Console.WriteLine("Error"); // } // }); var suggest = new string[]{"Get groceries", "Buy gas", "Post letter"}; PresentTextInputController( suggest, WatchKit.WKTextInputMode.AllowEmoji, (a) => { Console.WriteLine("Text was selected"); if (a != null && a.Count > 0) { enteredText = a.GetItem<NSObject>(0).ToString(); Console.WriteLine(" " + a.GetItem<NSObject>(0)); Name.SetText (a.GetItem<NSObject>(0).ToString()); entryMode = false; EnterText.SetTitle ("Save"); } else { Console.WriteLine("Error"); } }); } else { Console.WriteLine("EntryMode=false must save"); // TODO: save! TodoItemDatabase Database = null; var todo = new TodoItem{Name = enteredText, Done = false}; if (Database == null) { var FileManager = new NSFileManager (); var appGroupContainer = FileManager.GetContainerUrl ("group.co.conceptdev.WatchTodo"); var appGroupContainerPath = appGroupContainer.Path; Console.WriteLine ("agcpath: " + appGroupContainerPath); var sqliteFilename = "TodoSQLite.db3"; // string documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal); // Documents folder // string libraryPath = Path.Combine (documentsPath, "..", "Library"); // Library folder var path = Path.Combine(appGroupContainerPath, sqliteFilename); var conn = new SQLiteConnection (path); Database = new TodoItemDatabase(conn); } Database.SaveItem(todo); Database.Close(); PopController(); } }
public override void ViewDidLoad() { base.ViewDidLoad(); this.NavigationItem.SetRightBarButtonItem( new UIBarButtonItem(UIImage.FromFile("exitImg.png") , UIBarButtonItemStyle.Plain , (sender, args) => { NSUserDefaults.StandardUserDefaults.RemoveObject("Username"); NSUserDefaults.StandardUserDefaults.RemoveObject("Password"); UINavigationController navC = new UINavigationController(new LoginVC()); UIApplication.SharedApplication.KeyWindow.RootViewController = navC; UIApplication.SharedApplication.KeyWindow.MakeKeyAndVisible(); }) , true); NSNotificationCenter.DefaultCenter.AddObserver((NSString)"DownloadCount", getDownloadCount); this.NavigationController.NavigationBar.BarTintColor = UIColor.Red; this.Title = "Home"; var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); NSFileManager fileManager = NSFileManager.DefaultManager; NSError error; string[] countArray = fileManager.GetDirectoryContent(documents, out error); myDictionary = new NSDictionary("Seeit", "https://spo.mcd.com/sites/seeit_development3/brand/cognizant-test-brand-05242017?FromMobile=Y", "Local Files", countArray.Length); sharepointURLS_TblView.TableFooterView = new UIView(); sharepointURLS_TblView.Source = new TableSource(myDictionary, this); }
private static void _Init(object sender = null, EventArgs e = null) { string oldID = iCloudID; object token = null; if (NSFileManager.InstancesRespondToSelector("ubiquityIdentityToken")) { token = NSFileManager.DefaultManager().UbiquityIdentityToken(); } if (token == null) { iCloudID = null; _userDefaults.RemoveObject(ID_KEY); } else { NSData data = NSKeyedArchiver.ArchivedData(token); iCloudID = Convert.ToBase64String(data.ToByteArray()); _userDefaults.SetObject(iCloudID, ID_KEY); } Synchronize(); if (iCloudID != oldID) { if (_accountChangedHandlers != null) { _accountChangedHandlers(null, EventArgs.Empty); } } }
public override void DidFinishDownloading(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location) { Console.WriteLine("Finished"); Console.WriteLine("File downloaded in : {0}", location); NSFileManager fileManager = NSFileManager.DefaultManager; var URLs = fileManager.GetUrls(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User); NSUrl documentsDictionry = URLs [0]; NSUrl originalURL = downloadTask.OriginalRequest.Url; NSUrl destinationURL = documentsDictionry.Append("image1.png", false); NSError removeCopy; NSError errorCopy; fileManager.Remove(destinationURL, out removeCopy); bool success = fileManager.Copy(location, destinationURL, out errorCopy); if (success) { // we do not need to be on the main/UI thread to load the UIImage UIImage image = UIImage.FromFile(destinationURL.Path); InvokeOnMainThread(() => { controller.ImageView.Image = image; controller.ImageView.Hidden = false; controller.ProgressView.Hidden = true; }); } else { Console.WriteLine("Error during the copy: {0}", errorCopy.LocalizedDescription); } }
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); }
public void GetSkipBackupAttribute() { if ((Runtime.Arch == Arch.SIMULATOR) && RunningOnSnowLeopard) { Assert.Inconclusive("iOS simulator did not get libsystem_kernel.dylib before Lion"); } Assert.False(NSFileManager.GetSkipBackupAttribute(NSBundle.MainBundle.ExecutableUrl.ToString()), "MainBundle"); string filename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "DoNotBackupMe-NSFileManager"); try { File.WriteAllText(filename, "not worth a bit"); Assert.False(NSFileManager.GetSkipBackupAttribute(filename), "DoNotBackupMe-0"); NSFileManager.SetSkipBackupAttribute(filename, true); NSError error; Assert.True(NSFileManager.GetSkipBackupAttribute(filename, out error), "DoNotBackupMe-1"); Assert.Null(error, "error-1"); error = NSFileManager.SetSkipBackupAttribute(filename, false); Assert.False(NSFileManager.GetSkipBackupAttribute(filename), "DoNotBackupMe-2"); Assert.Null(error, "error-2"); } finally { // otherwise the attribute won't reset even if the file is overwritten File.Delete(filename); } }
public void GetUrlForUbiquityContainer() { #if !MONOMAC if ((Runtime.Arch == Arch.SIMULATOR) && RunningOnSnowLeopard) { Assert.Inconclusive("sometimes crash under the iOS simulator (generally on the SL/iOS5 bots)"); } #endif NSFileManager fm = new NSFileManager(); if (TestRuntime.CheckXcodeVersion(4, 5) && fm.UbiquityIdentityToken == null) { // UbiquityIdentityToken is a fast way to check if iCloud is enabled Assert.Pass("not iCloud enabled"); } NSUrl c = null; Exception e = null; ManualResetEvent evt = new ManualResetEvent(false); new Thread(() => { try { // From Apple's documentaiton: // Important: Do not call this method from your app’s main thread. Because this method might take a nontrivial amount of time to set up // iCloud and return the requested URL, you should always call it from a secondary thread. c = fm.GetUrlForUbiquityContainer(null); } catch (Exception ex) { e = ex; } finally { evt.Set(); } }) { IsBackground = true, }.Start(); if (evt.WaitOne(TimeSpan.FromSeconds(15))) { if (e != null) { throw e; } if (c == null) { Assert.Pass("not iCloud enabled"); // simulator or provisioning profile without iCloud enabled (old ones) } else { Assert.That(c.ToString(), Does.StartWith("file://localhost/private/var/mobile/Library/Mobile%20Documents"). Or.StartWith("file:///private/var/mobile/Library/Mobile%20Documents")); } } else { Assert.Pass("iCloud is probably not enabled"); // aborting is evil, so don't bother aborting the thread, just let it run its course } }
public static void RegisterLocalServices() { if (ServiceContainer.Resolve <ILogService>("logService", true) == null) { ServiceContainer.Register <ILogService>("logService", new ConsoleLogService()); } var preferencesStorage = new PreferencesStorageService(AppGroupId); var appGroupContainer = new NSFileManager().GetContainerUrl(AppGroupId); var liteDbStorage = new LiteDbStorageService( Path.Combine(appGroupContainer.Path, "Library", "bitwarden.db")); liteDbStorage.InitAsync(); var localizeService = new LocalizeService(); var broadcasterService = new BroadcasterService(); var messagingService = new MobileBroadcasterMessagingService(broadcasterService); var i18nService = new MobileI18nService(localizeService.GetCurrentCultureInfo()); var secureStorageService = new KeyChainStorageService(AppId, AccessGroup, () => ServiceContainer.Resolve <IAppIdService>("appIdService").GetAppIdAsync()); var cryptoPrimitiveService = new CryptoPrimitiveService(); var mobileStorageService = new MobileStorageService(preferencesStorage, liteDbStorage); var deviceActionService = new DeviceActionService(mobileStorageService, messagingService); var platformUtilsService = new MobilePlatformUtilsService(deviceActionService, messagingService, broadcasterService); ServiceContainer.Register <IBroadcasterService>("broadcasterService", broadcasterService); ServiceContainer.Register <IMessagingService>("messagingService", messagingService); ServiceContainer.Register <ILocalizeService>("localizeService", localizeService); ServiceContainer.Register <II18nService>("i18nService", i18nService); ServiceContainer.Register <ICryptoPrimitiveService>("cryptoPrimitiveService", cryptoPrimitiveService); ServiceContainer.Register <IStorageService>("storageService", mobileStorageService); ServiceContainer.Register <IStorageService>("secureStorageService", secureStorageService); ServiceContainer.Register <IDeviceActionService>("deviceActionService", deviceActionService); ServiceContainer.Register <IPlatformUtilsService>("platformUtilsService", platformUtilsService); }
public override void RowSelected(UITableView tableView, NSIndexPath indexPath) { var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); NSFileManager fileManager = NSFileManager.DefaultManager; NSError error; string[] listOfFiles = fileManager.GetDirectoryContent(documents, out error); string fileSelected = ""; foreach (string fileName in listOfFiles) { if (fileName.Equals(tableItems[indexPath.Row])) { fileSelected = System.IO.Path.Combine(documents, listOfFiles[indexPath.Row]); } } switch (fileSelected.Substring(fileSelected.Length - 3)) { case "jpg": loadImage(fileSelected); break; case "pdf": loadPDF(fileSelected); break; case "mp4": //playVideo(fileSelected); break; } tableView.DeselectRow(indexPath, true); }
/// <summary> /// Moves from URL. /// </summary> /// <param name="url">The URL.</param> /// <returns></returns> public Uri MoveFromUrl(Uri url) { return(null); #if PORTING string oldPath = url.Path; string newName = oldPath.LastPathComponent.StringByDeletingPathExtension(); string pathExtension = oldPath.LastPathComponent.PathExtension; string newPath = this.InboxPath.StringByAppendingPathComponent(oldPath.LastPathComponent); Exception error = null; if (!NSFileManager.DefaultManager().FileExistsAtPath(newPath)) { NSFileManager.DefaultManager().MoveItemAtPathToPathError(oldPath, newPath, error); } else { bool moved = false; for (int i = 1; (!moved && i < 100); i++) { string newName1 = $"{newName}-{i}.{pathExtension}"; newPath = this.InboxPath.StringByAppendingPathComponent(newName1); if (!NSFileManager.DefaultManager().FileExistsAtPath(newPath)) { moved = NSFileManager.DefaultManager().MoveItemAtPathToPathError(oldPath, newPath, error); } } } return(NSURL.FileURLWithPath(newPath)); #endif }
/// <summary> /// Callback method called by document picker when file has been picked; this is called /// up to iOS 10. /// </summary> /// <param name="sender">sender object (document picker)</param> /// <param name="args">event args</param> void DocumentPicker_DidPickDocument(object sender, UIDocumentPickedEventArgs args) { try { var securityEnabled = args.Url.StartAccessingSecurityScopedResource(); var doc = new UIDocument(args.Url); string name = doc.LocalizedName; string path = doc.FileUrl?.Path; args.Url.StopAccessingSecurityScopedResource(); // iCloud drive can return null for LocalizedName. if (name == null && path != null) { name = Path.GetFileName(path); } NSFileManager mg = new NSFileManager(); List <FileData> ls = new List <FileData>(); ls.Add(new FileData(path, name, mg.GetAttributes(path).Size.Value)); var tcs = Interlocked.Exchange(ref _tcs, null); tcs?.SetResult(ls); } catch (Exception ex) { // pass exception to task so that it doesn't get lost in the UI main loop var tcs = Interlocked.Exchange(ref _tcs, null); tcs.SetException(ex); } }
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 WriteImageToPath(UIImage image, string path) { NSFileManager.DefaultManager().RemoveItemAtPathError(path, null); NSData data = path.PathExtension().LowercaseString().IsEqualToString("png") ? UIImagePNGRepresentation(image) : UIImageJPEGRepresentation(image, 1.0); data.WriteToFileAtomically(path, true); }
public NSMutableArray GetMountedVolumes() { NSMutableArray volumeList = new NSMutableArray(); NSArray volKeys = NSArray.FromNSObjects( NSUrl.VolumeLocalizedNameKey, NSUrl.VolumeTotalCapacityKey, NSUrl.VolumeAvailableCapacityKey, NSUrl.VolumeIsBrowsableKey, NSUrl.VolumeURLKey, NSUrl.VolumeUUIDStringKey ); NSFileManager fileManager = new NSFileManager(); NSUrl[] volumeUrls = fileManager.GetMountedVolumes(volKeys, NSVolumeEnumerationOptions.None); NSByteCountFormatter byteFormatter = new NSByteCountFormatter(); byteFormatter.CountStyle = NSByteCountFormatterCountStyle.File; foreach(NSUrl volumeUrl in volumeUrls) { NSError volUrlError; NSObject volName; NSObject volIdentifer; NSObject volBrowsable; NSObject volBytesAvailable; NSObject volBytesTotal; volumeUrl.TryGetResource(NSUrl.VolumeLocalizedNameKey, out volName, out volUrlError); volumeUrl.TryGetResource(NSUrl.VolumeURLKey, out volIdentifer, out volUrlError); volumeUrl.TryGetResource(NSUrl.VolumeIsBrowsableKey, out volBrowsable, out volUrlError); volumeUrl.TryGetResource(NSUrl.VolumeAvailableCapacityKey, out volBytesAvailable, out volUrlError); volumeUrl.TryGetResource(NSUrl.VolumeTotalCapacityKey, out volBytesTotal, out volUrlError); NSNumber volBytesAvailableNum = (NSNumber)volBytesAvailable; NSNumber volBytesTotalNum = (NSNumber)volBytesTotal; byteFormatter.IncludesUnit = false; byteFormatter.IncludesCount = true; var volBytesAvailableCount = byteFormatter.Format(volBytesAvailableNum.LongValue); var volBytesTotalCount = byteFormatter.Format(volBytesTotalNum.LongValue); byteFormatter.IncludesUnit = true; byteFormatter.IncludesCount = false; var volBytesAvailableUnit = byteFormatter.Format(volBytesAvailableNum.LongValue); var volBytesTotalUnit = byteFormatter.Format(volBytesTotalNum.LongValue); NSNumber browsable = (NSNumber)volBrowsable; if (browsable.BoolValue) { volumeList.Add(new NSDictionary( "name", volName, "id", volIdentifer, "bytesAvailableCount", volBytesAvailableCount, "bytesAvailableUnit", volBytesAvailableUnit, "bytesTotalCount", volBytesTotalCount, "bytesTotalUnit", volBytesTotalUnit )); } } return volumeList; }
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); }
string GetFilePath(string filename) { var fileManger = new NSFileManager(); var url = fileManger.GetUrls(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User)[0]; return(url.Append(filename, false).Path); }
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> 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> 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); }
NSUrl CreateApplicationSupportDirectory() { NSFileManager fileManager = NSFileManager.DefaultManager; NSUrl[] URLs = fileManager.GetUrls(NSSearchPathDirectory.ApplicationSupportDirectory, NSSearchPathDomain.User); NSUrl url = URLs [URLs.Length - 1]; url = url.Append(ApplicationDocumentsDirectoryName, false); NSError error; NSDictionary properties = url.GetResourceValues(new NSString[] { NSUrl.IsDirectoryKey }, out error); if (properties != null) { var isDirectoryNumber = (NSNumber)properties [NSUrl.IsDirectoryKey]; if (isDirectoryNumber != null && !isDirectoryNumber.BoolValue) { Console.WriteLine("Could not access the application data folder."); return(null); } } else if (error.Code == (int)NSCocoaError.FileReadNoSuchFile) { bool ok = fileManager.CreateDirectory(url.Path, true, null); if (!ok) { Console.WriteLine("Error occured: {0}", error.LocalizedDescription); return(null); } } return(url); }
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 static void SetAttribute(String filePath) { if (!NSFileManager.GetSkipBackupAttribute(filePath)) { NSFileManager.SetSkipBackupAttribute(filePath, true); } }
public async Task <bool> RemoveFileAsync(string fileName) { try { var filePathCombine = await GetFileAsync(fileName); NSFileManager manager = new NSFileManager(); bool removed = false; if (manager.FileExists(filePathCombine)) { removed = manager.Remove(new NSUrl(filePathCombine, false), out _); } return(removed); } catch (System.Exception ex) { // Notification : LOCAL PUSH NOTIFICATION //DependencyService.Get<INotificationServices>().SendNotification( // ActivityType.EXCEPTION_OCCURRED.ToString(), // "EXCEPTION OCCURRED", "File:1", // ex.Message, // 1001); var exceptionHandler = new ExceptionHandler(typeof(FileDownloadService).FullName, ex); } return(false); }
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); }
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); } }
public override void DidFinishDownloading(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location) { Console.WriteLine("Finished"); Console.WriteLine("File downloaded in : {0}", location); NSFileManager fileManager = NSFileManager.DefaultManager; var URLs = fileManager.GetUrls(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User); NSUrl documentsDictionry = URLs[0]; NSUrl originalURL = downloadTask.OriginalRequest.Url; NSUrl destinationURL = documentsDictionry.Append(controller.FileName, false); NSError removeCopy; NSError errorCopy; fileManager.Remove(destinationURL, out removeCopy); bool success = fileManager.Copy(location, destinationURL, out errorCopy); if (success) { controller.Dismiss(); } else { Console.WriteLine("Error during the copy: {0}", errorCopy.LocalizedDescription); } }
public async Task <bool> SaveUrlDataToFile(string url, string destinationPath) { NSUrl nsUrl = new NSUrl(url); string fileName = nsUrl.LastPathComponent; //load the data NSData pdfData = NSData.FromUrl(nsUrl); if (pdfData == null) { Console.WriteLine("failed to fetch data for " + nsUrl.AbsoluteString + ". data came back null."); return(false); } //save the data NSError dataError; pdfData.Save(destinationPath, true, out dataError); if (dataError != null) { Console.WriteLine("error when saving data for " + nsUrl.AbsoluteString + ". " + dataError.ToString()); return(false); } else { Console.WriteLine("Data saved succesfully for " + nsUrl.AbsoluteString + " to " + destinationPath); //flag the data NSFileManager.SetSkipBackupAttribute(destinationPath, true); Console.WriteLine("Setting skip backup attribute for file: " + destinationPath); return(true); } }
/// /// ------------------------------------------------------------------------------------------------ /// Name WriteAsync /// /// <summary> Asynchronously writes the byte array to a file, overwriting or creating a new file. /// </summary> /// <param name="filePath"> The file path.</param> /// <param name="contents"> The binary data to write.</param> /// <param name="tryCount"> The amount of times the operation has been attempted.</param> /// /// <remarks> /// </remarks> /// ------------------------------------------------------------------------------------------------ /// public async Task WriteAsync(string filePath, byte[] contents, int tryCount = 0) { try { using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write)) await fs.WriteAsync(contents, 0, contents.Length); // NSFileManager.SetSkipBackupAttribute(filePath, true); } catch (Exception ex) { // Always try again if the exception is a sharing violation, unless the operation has been // attempted too many times already. if (tryCount > 5) { throw new Exception("Operation has failed too many times.", ex); } else if (ex.Message.StartsWith("Sharing violation", StringComparison.InvariantCulture) || tryCount == 0) { // Delay the thread for 2 seconds before trying again. await Task.Delay(2000); tryCount++; await WriteAsync(filePath, contents, tryCount); } else { throw ex; } } }
/// <summary> /// Gets called if the download has been completed. /// </summary> public override void DidFinishDownloading(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location) { // The download location will be a file location. var sourceFile = location.Path; // Construct a destination file name. var destFile = downloadTask.OriginalRequest.Url.AbsoluteString.Substring(downloadTask.OriginalRequest.Url.AbsoluteString.LastIndexOf("/") + 1); Console.WriteLine("DidFinishDownloading - Task: {0}, Source file: {1}", downloadTask.TaskIdentifier, sourceFile); // Copy over to documents folder. Note that we must use NSFileManager here! File.Copy() will not be able to access the source location. NSFileManager fileManager = NSFileManager.DefaultManager; // Create the filename var documentsFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); NSUrl destinationURL = NSUrl.FromFilename(Path.Combine(documentsFolderPath, destFile)); // Remove any existing file in our destination NSError error; fileManager.Remove(DownloadController.targetFilename, out error); bool success = fileManager.Copy(sourceFile, DownloadController.targetFilename, out error); if (!success) { Console.WriteLine("Error during the copy: {0}", error.LocalizedDescription); } this.InvokeOnMainThread(() => this.controller.LoadImage()); }
public Task UpdateMultipleEntities(IEnumerable <Session> data) { return(Task.Run(() => { var fileManager = new NSFileManager(); var appGroupContainer = fileManager.GetContainerUrl($"group.{AboutThisApp.PackageName}"); var appGroupContainerPath = appGroupContainer.Path; var sessionsFilePath = Path.Combine(appGroupContainerPath, "sessions.json"); if (fileManager.FileExists(sessionsFilePath)) { NSError error; fileManager.Remove(sessionsFilePath, out error); } var attributes = new NSFileAttributes { Type = NSFileType.Regular }; var json = JsonConvert.SerializeObject(data.Where(s => s.IsFavorite).ToList()); var fileData = NSData.FromString(json); fileManager.CreateFile(sessionsFilePath, fileData, attributes); var url = NSUrl.FromFilename(sessionsFilePath); url.SetResource(NSUrl.IsExcludedFromBackupKey, new NSNumber(true)); var settings = new NSUserDefaults($"group.{AboutThisApp.PackageName}", NSUserDefaultsType.SuiteName); settings.SetBool(true, "FavoritesInitialized"); settings.Synchronize(); UpdateWidget(); })); }
public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options) { var tabController = Window.RootViewController as UINavigationController; if (AppSettings.User.IsAuthenticated) { var urlCollection = url.ToString().Replace("steepshot://", string.Empty); var nsFileManager = new NSFileManager(); var imageData = nsFileManager.Contents(urlCollection); var sharedPhoto = UIImage.LoadFromData(imageData); var inSampleSize = ImageHelper.CalculateInSampleSize(sharedPhoto.Size, Core.Constants.PhotoMaxSize, Core.Constants.PhotoMaxSize); var deviceRatio = UIScreen.MainScreen.Bounds.Width / UIScreen.MainScreen.Bounds.Height; var x = ((float)inSampleSize.Width - Core.Constants.PhotoMaxSize * (float)deviceRatio) / 2f; sharedPhoto = ImageHelper.CropImage(sharedPhoto, 0, 0, (float)inSampleSize.Width, (float)inSampleSize.Height, inSampleSize); var descriptionViewController = new DescriptionViewController(new List <Tuple <NSDictionary, UIImage> >() { new Tuple <NSDictionary, UIImage>(null, sharedPhoto) }, "jpg"); tabController.PushViewController(descriptionViewController, false); } else { tabController.PushViewController(new WelcomeViewController(), false); } return(true); }
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) { Current = this; wormHole = new Wormhole ("group.co.conceptdev.WatchTodo", "messageDir"); var FileManager = new NSFileManager (); var appGroupContainer = FileManager.GetContainerUrl ("group.co.conceptdev.WatchTodo"); var appGroupContainerPath = appGroupContainer.Path; Console.WriteLine ("agcpath: " + appGroupContainerPath); var sqliteFilename = "TodoSQLite.db3"; // App Group storage, shared with Watch Extension var path = Path.Combine(appGroupContainerPath, sqliteFilename); var conn = new SQLiteConnection (path); Database = new TodoItemDatabase(conn); // HACK: temporary population of data if (Database.GetItems ().Count() == 0) { Database.SaveItem (new TodoItem { Name = "buy pineapple" }); Database.SaveItem (new TodoItem { Name = "buy dragon fruit", Done = true }); Database.SaveItem (new TodoItem { Name = "buy honeydew" }); Database.SaveItem (new TodoItem { Name = "buy rockmelon" }); } return true; }
public string GetFolderPath (EtoSpecialFolder folder) { NSSearchPathDirectory dir; NSSearchPathDomain domain; Convert (folder, out dir, out domain); var manager = new NSFileManager(); NSError error; var path = manager.GetUrl(dir, domain, null, false, out error); return path.Path; }
string CreateAppDirectory(NSSearchPathDirectory targetDir, string subDir = "Data") { NSError err; var fm = new NSFileManager(); var url = fm.GetUrl(targetDir, NSSearchPathDomain.All, null, true, out err); var ret = Path.Combine(url.RelativePath, NSBundle.MainBundle.BundleIdentifier, subDir); if (!Directory.Exists(ret)) Directory.CreateDirectory(ret); return ret; }
string CreateAppDirectory(NSSearchPathDirectory targetDir, string subDir = "BlobCache") { NSError err; var fm = new NSFileManager(); var url = fm.GetUrl(targetDir, NSSearchPathDomain.All, null, true, out err); var ret = Path.Combine(url.RelativePath, BlobCache.ApplicationName, subDir); if (!Directory.Exists(ret)) _inner.CreateRecursive(ret).Wait(); return ret; }
private void getSettings() { var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments); var library = System.IO.Path.Combine (documents, "..", "Library"); var urlpath = System.IO.Path.Combine (library, "audioRecording.wav"); session = AVAudioSession.SharedInstance (); session.SetCategory (AVAudioSessionCategory.PlayAndRecord); url = new NSUrl (urlpath, false); NSFileManager manager = new NSFileManager (); NSError error = new NSError (new NSString ("world"), 1); //if there is a file at the save location, delete it so we can save there if (manager.FileExists (urlpath)) { Console.WriteLine ("Deleting File"); manager.Remove (urlpath, out error); Console.WriteLine ("Deleted File"); } NSObject[] values = new NSObject[] { NSNumber.FromFloat (44100.0f), //Sample Rate NSNumber.FromInt32 ((int)MonoTouch.AudioToolbox.AudioFormatType.LinearPCM), //AVFormat NSNumber.FromInt32 (2), //Channels NSNumber.FromInt32 (16), //PCMBitDepth NSNumber.FromBoolean (false), //IsBigEndianKey NSNumber.FromBoolean (false) //IsFloatKey }; NSObject[] keys = new NSObject[] { AVAudioSettings.AVSampleRateKey, AVAudioSettings.AVFormatIDKey, AVAudioSettings.AVNumberOfChannelsKey, AVAudioSettings.AVLinearPCMBitDepthKey, AVAudioSettings.AVLinearPCMIsBigEndianKey, AVAudioSettings.AVLinearPCMIsFloatKey }; settings = NSDictionary.FromObjectsAndKeys (values, keys); recorder = AVAudioRecorder.ToUrl (url, settings, out error); }
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 void Awake(NSObject context) { base.Awake (context); // Configure interface objects here. Console.WriteLine ("{0} awake with context", this); var FileManager = new NSFileManager (); var appGroupContainer = FileManager.GetContainerUrl ("group.com.conceptdevelopment.watchinsta"); var appGroupContainerPath = appGroupContainer.Path; Console.WriteLine ("agcpath: " + appGroupContainerPath); var d = new DirectoryInfo (appGroupContainerPath); foreach (var f in d.EnumerateFiles()) { Console.WriteLine (f); lastImageFilename = f.FullName; lastImageName = f.Name; } }
public override void Awake (NSObject context) { base.Awake (context); Tweets = new List<Tweet> (); // Configure interface objects here. Console.WriteLine ("{0} awake with context", this); var FileManager = new NSFileManager (); var appGroupContainer = FileManager.GetContainerUrl ("group.com.refractored.hanselman"); if (appGroupContainer == null) { Console.WriteLine("You must go into apple developer console and create a new app group"); } else { Path = System.IO.Path.Combine(appGroupContainer.Path, "tweets.xml"); Console.WriteLine("agcpath: " + Path); } }
static Task MoveToiCloud(NSUrl sourceUrl, NSUrl destinationURL) { if (NSFileManager.DefaultManager.UbiquityIdentityToken == null) return Task.FromResult<NSUrl> (null); var tcs = new TaskCompletionSource<object>(); // Upload the file to iCloud on a background queue. ThreadPool.QueueUserWorkItem (_ => { NSError error; NSFileManager fileManager = new NSFileManager(); bool success = fileManager.SetUbiquitous(true, sourceUrl, destinationURL, out error); if (!success) Console.WriteLine (error); tcs.SetResult(null); }); return tcs.Task; }
partial void Save() { if (Database == null) { var FileManager = new NSFileManager (); var appGroupContainer = FileManager.GetContainerUrl ("group.co.conceptdev.WatchTodo"); var appGroupContainerPath = appGroupContainer.Path; Console.WriteLine ("agcpath: " + appGroupContainerPath); var sqliteFilename = "TodoSQLite.db3"; // string documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal); // Documents folder // string libraryPath = Path.Combine (documentsPath, "..", "Library"); // Library folder var path = Path.Combine(appGroupContainerPath, sqliteFilename); var conn = new SQLiteConnection (path); Database = new TodoItemDatabase(conn); } Console.WriteLine ("Save the todo " + todo.Name); Database.SaveItem(todo.As()); PopController(); }
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; }
void ReadQueryResults () { var fm = new NSFileManager (); var deadIndex = new HashSet<string> (fileIndex.Keys); var newList = new List<CloudFile> (); var newIndex = new Dictionary<string, IFile> (); // Console.WriteLine ("-------------- Received iCloud"); foreach (var item in query.Results) { var cf = new CloudFile (item, documentsUrl); var key = cf.Path; if (deadIndex.Contains (key)) { deadIndex.Remove (key); } else { newList.Add (cf); } newIndex[key] = cf; // // Add a "file" for directories // var dir = Path.GetDirectoryName (cf.Path); if (!string.IsNullOrEmpty (dir) && !newIndex.ContainsKey (dir)) newIndex [dir] = new DeviceFile (dir, documentsUrl.Path); // Console.WriteLine (cf); } foreach (var f in newList) { if (!f.IsDownloaded) { NSError error; fm.StartDownloadingUbiquitous (f.LocalUrl, out error); } } fileIndex = newIndex; IsSyncing = false; if (firstQueryResult != null) { var t = firstQueryResult; firstQueryResult = null; t.SetResult (null); } var ev = FilesChanged; if (ev != null) { ev (this, EventArgs.Empty); } }
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 convertAudio () { var success = DoConvertFile (sourceURL, destinationURL, outputFormat, sampleRate); BeginInvokeOnMainThread (delegate { activityIndicator.StopAnimating (); }); if (!success) { var fm = new NSFileManager (); if (fm.FileExists (destinationFilePath)) { NSError error; fm.Remove (destinationFilePath, out error); } BeginInvokeOnMainThread (updateUI); } else { BeginInvokeOnMainThread (playAudio); } }
public static void deleteVideo(string vidToDelete) { NSFileManager manager = new NSFileManager (); NSError error = new NSError (); //delete the file if it is already there if (manager.FileExists (vidToDelete)) { manager.Remove (vidToDelete, out error); } }
void MakeItemUbiquitousAtURL(NSUrl sourceURL) { string destinationFileName = sourceURL.LastPathComponent; NSUrl destinationURL = DocumentsDirectory.Append (destinationFileName, false); // Upload the file to iCloud on a background queue. ThreadPool.QueueUserWorkItem (_ => { NSFileManager fileManager = new NSFileManager(); NSError error; bool success = fileManager.SetUbiquitous(true, sourceURL, destinationURL, out error); // If the move wasn't successful, try removing the item locally since the document may already exist in the cloud. if (!success) fileManager.Remove(sourceURL, out error); }); }
void startStopPushed(object sender, EventArgs ea) { if (!weAreRecording) { var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments); var library = System.IO.Path.Combine (documents, "..", "Library"); var urlpath = System.IO.Path.Combine (library, "sweetMovieFilm.mov"); NSUrl url = new NSUrl (urlpath, false); NSFileManager manager = new NSFileManager (); NSError error = new NSError (); if (manager.FileExists (urlpath)) { Console.WriteLine ("Deleting File"); manager.Remove (urlpath, out error); Console.WriteLine ("Deleted File"); } AVCaptureFileOutputRecordingDelegate avDel= new AVCaptureFileOutputRecordingDelegate (); output.StartRecordingToOutputFile(url, avDel); Console.WriteLine (urlpath); weAreRecording = true; btnStartRecording.SetTitle("Stop Recording", UIControlState.Normal); } //we were already recording. Stop recording else { output.StopRecording (); Console.WriteLine ("stopped recording"); weAreRecording = false; btnStartRecording.SetTitle("Start Recording", UIControlState.Normal); } }
public static void DeleteImage(string imagefilename) { if (!string.IsNullOrEmpty (imagefilename)) { string name = imagefilename.Substring (0, imagefilename.Length - 4); var documentsDirectory = Environment.GetFolderPath (Environment.SpecialFolder.Personal); var picname = name + ".png"; var thumbpicname = name + "_thumb.png"; string pngfileName = System.IO.Path.Combine (documentsDirectory, picname); string thumbpngfileName = System.IO.Path.Combine (documentsDirectory, thumbpicname); NSFileManager fm = new NSFileManager (); NSError err = null; if (fm.IsDeletableFile (pngfileName)) { fm.Remove (pngfileName, out err); //TODO use error for something sensible } err = null; if (fm.IsDeletableFile (thumbpngfileName)) { fm.Remove (thumbpngfileName, out err); //TODO use errormsg for something sensible. } } }
public static Boolean vidExists(string vidCheck) { NSFileManager mgr = new NSFileManager (); if (mgr.FileExists (vidCheck)) { return true; } return false; }
public override void ViewDidAppear(bool animated) { base.ViewDidAppear (animated); var FileManager = new NSFileManager (); var appGroupContainer = FileManager.GetContainerUrl ("group.com.conceptdevelopment.watchinsta"); var appGroupContainerPath = appGroupContainer.Path; Console.WriteLine ("agcpath: " + appGroupContainerPath); IEnumerable<Account> accounts = AccountStore.Create ().FindAccountsForService ("Instagram"); string token = ""; acct = (from a in accounts select a).FirstOrDefault (); if (acct != null) { token = acct.Properties ["access_token"]; var request = new OAuth2Request ( "GET", new Uri ("https://api.instagram.com/v1/users/self/feed?access_token=" + token) , null , acct);//eventArgs.Account); request.GetResponseAsync ().ContinueWith (t => { if (t.IsFaulted) Console.WriteLine ("Error: " + t.Exception.InnerException.Message); else { string json = t.Result.GetResponseText (); Console.WriteLine (json); var root = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject> (json); var webClient = new WebClient(); var count = Math.Min(5, root.data.Count); var i = 0; var inst = root.data[i]; var thumb = inst.images.thumbnail; var url = new Uri(thumb.url); Console.WriteLine(inst.caption.text); Console.WriteLine("download: " + inst.images.thumbnail.url); webClient.DownloadDataCompleted += (s, e) => { Console.WriteLine("download completed"); if (e.Error == null) { var bytes = e.Result; // get the downloaded data string documentsPath = appGroupContainerPath; //Environment.GetFolderPath(Environment.SpecialFolder.Personal); string localFilename = "insta-"+DateTime.Now.Ticks+".png"; string localPath = Path.Combine (documentsPath, localFilename); File.WriteAllBytes (localPath, bytes); // writes to local storage Console.WriteLine ("saved to: " + localPath); InvokeOnMainThread (() => { instagramImageView.Image = UIImage.FromFile(localPath); }); } else { Console.WriteLine(e.Error); } // other loops if (i < count) { inst = root.data[i]; thumb = inst.images.thumbnail; url = new Uri(thumb.url); Console.WriteLine(inst.caption.text); Console.WriteLine(inst.images.thumbnail.url); webClient.DownloadDataAsync(url); i++; } }; // first loop webClient.DownloadDataAsync(url); } }); } else { // // // http://instagram.com/developer/clients/manage/ // var auth = new OAuth2Authenticator ( clientId: "YOU_NEED_YOUR_INSTAGRAM_DEV_CLIENTID_HERE", scope: "basic", authorizeUrl: new Uri ("https://api.instagram.com/oauth/authorize/"), redirectUrl: new Uri ("http://your-redirect-url.net/")); auth.Completed += (sender, eventArgs) => { // We presented the UI, so it's up to us to dimiss it on iOS. DismissViewController (true, null); if (eventArgs.IsAuthenticated) { // Use eventArgs.Account to do wonderful things acct = eventArgs.Account; AccountStore.Create ().Save (eventArgs.Account, "Instagram"); token = eventArgs.Account.Properties ["access_token"]; var request = new OAuth2Request ("GET", new Uri ("https://api.instagram.com/v1/users/self/feed?access_token=" + token) , null, acct);//eventArgs.Account); request.GetResponseAsync ().ContinueWith (t => { if (t.IsFaulted) Console.WriteLine ("Error: " + t.Exception.InnerException.Message); else { string json = t.Result.GetResponseText (); Console.WriteLine (json); } }); } else { // The user cancelled } }; PresentViewController (auth.GetUI (), true, null); } }