// // Load support: // Override one of ReadFromData, ReadFromFileWrapper or ReadFromUrl // public override bool ReadFromData(NSData data, string typeName, out NSError outError) { outError = null; Console.WriteLine("About to read data of type {0}", typeName); NSMutableArray newArray = null; try { newArray = (NSMutableArray)NSKeyedUnarchiver.UnarchiveObject(data); } catch (Exception ex) { Console.WriteLine("Error loading file: Exception: {0}", ex.Message); if (outError != null) { NSDictionary d = NSDictionary.FromObjectAndKey(new NSString("The data is corrupted."), NSError.LocalizedFailureReasonErrorKey); outError = NSError.FromDomain(NSError.OsStatusErrorDomain, -4, d); } return(false); } this.Employees = newArray; return(true); // Default template code // outError = NSError.FromDomain(NSError.OsStatusErrorDomain, -4); // return false; }
public static OfflinePack ToFormsPack(this MGLOfflinePack mbPack) { if (mbPack == null) { return(null); } var output = new OfflinePack { Progress = mbPack.Progress.ToFormsProgress(), State = (OfflinePackState)mbPack.State, Handle = mbPack.Handle }; var mbRegion = mbPack.Region; var region = ObjCRuntime.Runtime.GetINativeObject <MGLTilePyramidOfflineRegion>(mbRegion.Handle, false); output.Region = region?.ToFormsRegion(); if (mbPack.Context != null) { var info = new Dictionary <string, string>(); NSDictionary userInfo = NSKeyedUnarchiver.UnarchiveObject(mbPack.Context) as NSDictionary; foreach (NSObject key in userInfo.Keys) { info.Add(key.ToString(), userInfo[key].ToString()); } output.Info = info; } return(output); }
private void GetDocumentSaved() { NSUserDefaults defaults = NSUserDefaults.StandardUserDefaults; NSData encodedObject = (NSData)defaults.ValueForKey(DocumentSavedKey); // Check if there are documents saved if (encodedObject == null) { return; } // Get documents saved and build the list NSMutableArray listDoc = (NSMutableArray)NSKeyedUnarchiver.UnarchiveObject(encodedObject); DocumentsList = new List <Document>(); for (nuint i = 0; i < listDoc.Count; i++) { DocumentArchive docSaved = listDoc.GetItem <DocumentArchive>(i); // Build Document c# object form DocumentArchive NsObject Document doc = new Document(); doc.Name = docSaved.Name; doc.ServerRelativeUrl = docSaved.ServerRelativeUrl; doc.BytesArray = docSaved.BytesArray; DocumentsList.Add(doc); } // Load data and reload TableView tableView.Source = new DocumentTableDataSource(this.DocumentsList, this); tableView.ReloadData(); }
// Loads the data from `NSUserDefaults`. void LoadData() { UserDefaultsAccessQueue.DispatchSync(() => { NSData archivedData = UserDefaults.DataForKey(StorageDescriptor.Key); try { // Let the derived classes handle the specifics of // putting the unarchived data in the correct format. // This is necessary because the derived classes // (SoupMenuManager, SoupOrderMenuManager) are using // generic data formats (NSMutableSet<T> or NSMutableArray<T>) // and these types cannot be casted directly from the // deserialized data. NSObject unarchivedData = NSKeyedUnarchiver.UnarchiveObject(archivedData); FinishUnarchiving(unarchivedData); } catch (Exception e) { if (!(e is null)) { Console.WriteLine($"Error: {e.Message}"); } } }); }
public void GetUnarchivedObject_TypeWrappers() { TestRuntime.AssertXcodeVersion(10, 0); NSDictionary <NSString, NSString> testValues = new NSDictionary <NSString, NSString> ((NSString)"1", (NSString)"a"); NSData data = NSKeyedArchiver.ArchivedDataWithRootObject(testValues, true, out NSError error); Assert.IsNull(error); Type dictionaryType = typeof(NSDictionary <NSString, NSString>); Class dictionaryClass = new Class(dictionaryType); NSObject o = NSKeyedUnarchiver.GetUnarchivedObject(dictionaryClass, data, out error); Assert.IsNotNull(o); Assert.IsNull(error, "GetUnarchivedObject - Class"); o = NSKeyedUnarchiver.GetUnarchivedObject(new NSSet <Class> (new Class [] { dictionaryClass }), data, out error); Assert.IsNotNull(o); Assert.IsNull(error, "GetUnarchivedObject - NSSet<Class>"); o = NSKeyedUnarchiver.GetUnarchivedObject(dictionaryType, data, out error); Assert.IsNotNull(o); Assert.IsNull(error, "GetUnarchivedObject - Type"); o = NSKeyedUnarchiver.GetUnarchivedObject(new Type [] { dictionaryType }, data, out error); Assert.IsNotNull(o); Assert.IsNull(error, "GetUnarchivedObject - Type []"); }
public override void StartLoading() { if (!UseCache) { var connectionRequest = (NSMutableUrlRequest)Request.MutableCopy; // we need to mark this request with our header so we know not to handle it in +[NSURLProtocol canInitWithRequest:]. connectionRequest.SetValueForKey("", MtRnCachingUrlHeader); var connection = NSUrlConnection.FromRequest(connectionRequest, this); Connection = connection; } else { var cache = NSKeyedUnarchiver.UnarchiveFile(CachePathForRequest(this.Request)) as MtRnCachedData; if (cache != null) { var data = cache.Data; var response = cache.Response; var redirectRequest = cache.RedirectRequest; if (redirectRequest != null) { this.Client.Redirected(this, redirectRequest, response); } else { Client.ReceivedResponse(this, response, NSUrlCacheStoragePolicy.NotAllowed); Client.DataLoaded(this, data); Client.FinishedLoading(this); } } else { this.Client.FailedWithError(NSError.FromDomain("TODO", NSUrlError.CannotConnectToHost)); } } }
// // Load support: // Override one of ReadFromData, ReadFromFileWrapper or ReadFromUrl // public override bool ReadFromData(NSData data, string typeName, out NSError outError) { outError = null; Console.WriteLine("About to read data of type {0}", typeName); NSMutableArray newArray = null; try { newArray = (NSMutableArray)NSKeyedUnarchiver.UnarchiveObject(data); } catch (Exception ex) { Console.WriteLine("Error loading file: Exception: {0}", ex.Message); if (outError != null) { NSDictionary d = NSDictionary.FromObjectAndKey(new NSString("The data is corrupted."), NSError.LocalizedFailureReasonErrorKey); outError = NSError.FromDomain(NSError.OsStatusErrorDomain, -4, d); } return(false); } this.Cars = newArray; // For Revert to Saved. Have to point the array controller to the new array. if (arrayController != null) { arrayController.Content = this.Cars; } return(true); }
public override bool LoadFromContents(NSObject contents, string typeName, out NSError outError) { outError = null; List deserializedList = (List)NSKeyedUnarchiver.UnarchiveObject((NSData)contents); if (deserializedList != null) { List = deserializedList; return(true); } outError = new NSError(NSError.CocoaErrorDomain, (int)NSCocoaError.FileReadCorruptFile, NSDictionary.FromObjectsAndKeys( new NSObject[] { (NSString)"Could not read file", (NSString)"File was in an invalid format" }, new NSObject[] { NSError.LocalizedDescriptionKey, NSError.LocalizedFailureReasonErrorKey } )); return(false); }
public void EncodeDecodeTest() { var buffer = new byte[] { 3, 14, 15 }; var obj = new NSString(); byte[] data; var ptr = Marshal.AllocHGlobal(buffer.Length); for (int i = 0; i < buffer.Length; i++) { Marshal.WriteByte(ptr, i, buffer [i]); } using (var mutableData = new NSMutableData(1024)) { using (var coder = new NSKeyedArchiver(mutableData)) { coder.Encode(obj, "obj"); coder.Encode(buffer, "buffer"); coder.Encode(Int32.MaxValue, "int32"); coder.Encode(float.MaxValue, "float"); coder.Encode(double.MaxValue, "double"); coder.Encode(true, "bool"); coder.Encode(long.MaxValue, "long"); coder.Encode(buffer, 2, 1, "buffer2"); coder.Encode(nint.MaxValue, "nint"); coder.EncodeBlock(ptr, buffer.Length, "block"); coder.FinishEncoding(); } using (var decoder = new NSKeyedUnarchiver(mutableData)) { Assert.IsNotNull(decoder.DecodeObject("obj")); var buf = decoder.DecodeBytes("buffer"); Assert.AreEqual(buf.Length, buffer.Length, "buffer.length"); for (int i = 0; i < buf.Length; i++) { Assert.AreEqual(buf [i], buffer [i], "buffer [" + i.ToString() + "]"); } Assert.AreEqual(Int32.MaxValue, decoder.DecodeInt("int32")); Assert.AreEqual(float.MaxValue, decoder.DecodeFloat("float")); Assert.AreEqual(true, decoder.DecodeBool("bool")); Assert.AreEqual(long.MaxValue, decoder.DecodeLong("long")); buf = decoder.DecodeBytes("buffer2"); Assert.AreEqual(buf.Length, buffer.Length, "buffer2.length"); for (int i = 0; i < buf.Length; i++) { Assert.AreEqual(buf [i], buffer [i], "buffer2 [" + i.ToString() + "]"); } Assert.AreEqual(nint.MaxValue, decoder.DecodeNInt("nint")); buf = decoder.DecodeBytes("block"); Assert.AreEqual(buf.Length, buffer.Length, "block.length"); for (int i = 0; i < buf.Length; i++) { Assert.AreEqual(buf [i], buffer [i], "block [" + i.ToString() + "]"); } } } Marshal.FreeHGlobal(ptr); }
public NSString getMessage(NSData data) { NSKeyedUnarchiver unarchiver = new NSKeyedUnarchiver(data); NSDictionary dictionary = (NSDictionary)unarchiver.DecodeObject(); NSString value = (NSString)dictionary.ObjectForKey(new NSString("msg")); return(value); }
public void RestoreValues() { if (NSKeyedUnarchiver.UnarchiveFile(archiveLocation) is Person retrievedPersonData) { FirstName = retrievedPersonData.FirstName; LastName = retrievedPersonData.LastName; } }
partial void LoadExperience() { if (DataFromFile == null) { Debug.WriteLine("Map data should already be verified to exist before Load button is enabled."); return; } try { var data = DataFromFile; ARWorldMap worldMap = (ARWorldMap)NSKeyedUnarchiver.GetUnarchivedObject(typeof(ARWorldMap), data, out var err); if (err != null) { Debug.WriteLine("No ARWorldMap in archive."); return; } // Display the snapshot image stored in the world map to aid user in relocalizing. var snapshotData = worldMap.GetSnapshotAnchor()?.ImageData; using (var snapshot = UIImage.LoadFromData(snapshotData)) { if (snapshot != null) { _snapShotThumbnail.Image = snapshot; } else { Debug.WriteLine("No snapshot image in world map"); } } // Remove the snapshot anchor from the world map since we do not need it in the scene. worldMap.Anchors = worldMap.Anchors.Where(anchor => anchor.GetType() != typeof(SnapshotAnchor)).ToArray(); var configuration = new ARWorldTrackingConfiguration { PlaneDetection = ARPlaneDetection.Horizontal, EnvironmentTexturing = AREnvironmentTexturing.Automatic, InitialWorldMap = worldMap, }; _sceneView.Session.Run(configuration, ARSessionRunOptions.ResetTracking | ARSessionRunOptions.RemoveExistingAnchors); // Run the view's session isRelocalizingMap = true; objAnchor = null; } catch (Exception ex) { Debug.WriteLine($"Can't unarchive ARWorldMap from file data: {ex.Message}"); return; } Debug.WriteLine($"Success: Loaded world scene from {MapSaveURL}"); }
// Loads the OIDAuthState from NSUSerDefaults. private void LoadState() { // loads OIDAuthState from NSUSerDefaults var archivedAuthState = (NSData)NSUserDefaults.StandardUserDefaults[kAppAuthExampleAuthStateKey]; if (archivedAuthState != null) { AuthState = (AuthState)NSKeyedUnarchiver.UnarchiveObject(archivedAuthState); } }
public static Optional <NSEvent> TryParse(IBinaryMessage message) { return(message.TryParse(Name, reader => { var length = reader.ReadInt32(); var data = reader.ReadBytes(length); var nsData = NSData.FromArray(data); return (NSEvent)NSKeyedUnarchiver.UnarchiveObject(nsData); })); }
private NSArray getTrackableEvents(string key) { var eventArrayData = userDefaults.ValueForKey(new NSString(key)) as NSData; if (eventArrayData == null) { return(new NSArray()); } return(NSKeyedUnarchiver.UnarchiveObject(eventArrayData) as NSArray); }
public string UnarchiveText(string filename) { var obj = NSKeyedUnarchiver.UnarchiveFile(GetFilePath(filename)); if (obj == null) { return(null); } else { return(((NSString)obj).ToString()); } }
public static TimedColor Create(NSData timedColor) { var data = NSKeyedUnarchiver.UnarchiveTopLevelObject(timedColor, out NSError error); if (data is NSDictionary dictionary) { return(new TimedColor(dictionary)); } else { throw new Exception("Failed to unarchive a timedColor dictionary!"); } }
// Load stored scores from disk public void loadStoredScores() { NSArray unarchivedObj = (NSArray)NSKeyedUnarchiver.UnarchiveFile(this.storedScoresFilename); if (unarchivedObj != null) { storedScores = (NSMutableArray)unarchivedObj; this.resubmitSotredScores(); } else { storedScores = new NSMutableArray(); } }
NSObject FetchStoredUbiquityIdentityToken() { NSObject storedToken = null; // Determine if the iCloud account associated with this device has changed since the last time the user launched the app. var tokenArchive = (NSData)NSUserDefaults.StandardUserDefaults[StoredUbiquityIdentityTokenKey]; if (tokenArchive != null) { storedToken = NSKeyedUnarchiver.UnarchiveObject(tokenArchive); } return(storedToken); }
public static SCNParticleSystem LoadParticleSystemWithName(string name, string paticleImageName = "") { string path = string.Format("level/effects/{0}.scnp", name); path = PathForArtResource(path); var newSystem = (SCNParticleSystem)NSKeyedUnarchiver.UnarchiveFile(path); if (!string.IsNullOrEmpty(paticleImageName)) { newSystem.ParticleImage = (NSString)PathForArtResource(string.Format("level/effects/{0}.png", paticleImageName)); } return(newSystem); }
// Load stored achievements and attempt to submit them public void loadSotredAchievements() { if (storedAchievements == null) { NSMutableDictionary unarchivedObj = (NSMutableDictionary)NSKeyedUnarchiver.UnarchiveFile(this.storedAchievementsFilename); if (unarchivedObj != null) { this.resubmitStoredAchievements(); } else { storedAchievements = new NSMutableDictionary(); } } }
public void Exceptions() { var data = NSData.FromString("dummy string"); if (TestRuntime.CheckXcodeVersion(7, 0)) { // iOS9 does not throw if it cannot get correct data, it simply returns null (much better) Assert.Null(NSKeyedUnarchiver.UnarchiveFile(Path.Combine(NSBundle.MainBundle.ResourcePath, "basn3p08.png")), "UnarchiveFile"); Assert.Null(NSKeyedUnarchiver.UnarchiveObject(data), "UnarchiveObject"); } else { Assert.Throws <PlatformException> (() => NSKeyedUnarchiver.UnarchiveFile(Path.Combine(NSBundle.MainBundle.ResourcePath, "basn3p08.png")), "UnarchiveFile"); Assert.Throws <PlatformException> (() => NSKeyedUnarchiver.UnarchiveObject(data), "UnarchiveObject"); } }
public void CtorNSCoder () { // NSNumber conforms to NSCoding - so it's .ctor(NSCoder) is usable using (var n = new NSNumber (-1)) using (var d = new NSMutableData ()) { using (var a = new NSKeyedArchiver (d)) { n.EncodeTo (a); a.FinishEncoding (); } using (var u = new NSKeyedUnarchiver (d)) using (var n2 = new NSNumber (u)) { // so we can re-create an instance from it Assert.That (n.Int32Value, Is.EqualTo (-1), "Value"); } } }
public override bool AcceptDrop(NSTableView tableView, NSDraggingInfo info, nint row, NSTableViewDropOperation dropOperation) { NSData rowData = info.DraggingPasteboard.GetDataForType(DungeonToolsConstants.ECOUNTER_INITIATIVE_DRAG_DROP_TYPE); if (rowData == null) { return(false); } NSIndexSet dataArray = NSKeyedUnarchiver.UnarchiveObject(rowData) as NSIndexSet; tableView.BeginUpdates(); SwapCreatures(dataArray, (int)row); tableView.ReloadData(); tableView.EndUpdates(); return(true); }
public void load() { Boolean hasFile = NSFileManager.defaultManager.fileExistsAtPath(_dataFileName); if (hasFile) { NSData data = NSData.dataWithContentsOfFile(_dataFileName) options(0) error(null); this.tasks = NSKeyedUnarchiver.unarchiveObjectWithData(data); NSLog("Data has been loaded from local file (%@)", _dataFileName); } else { this.generateTestData(); NSLog("Test data has been generated"); } }
static string FetchAdjustmentFilterName(PHContentEditingInput contentEditingInput) { string filterName = null; try { PHAdjustmentData adjustmentData = contentEditingInput.AdjustmentData; if (adjustmentData != null) { filterName = (NSString)NSKeyedUnarchiver.UnarchiveObject(adjustmentData.Data); } } catch (Exception exception) { Console.WriteLine("Exception decoding adjustment data: {0}", exception); } return(filterName); }
public void StartContentEditing(PHContentEditingInput input, UIImage placeholderImage) { // Present content for editing and keep the contentEditingInput for use when closing the edit session. // If you returned true from CanHandleAdjustmentData(), contentEditingInput has the original image and adjustment data. // If you returned false, the contentEditingInput has past edits "baked in". contentEditingInput = input; // Load input image switch (contentEditingInput.MediaType) { case PHAssetMediaType.Image: inputImage = contentEditingInput.DisplaySizeImage; break; case PHAssetMediaType.Video: inputImage = ImageFor(contentEditingInput.AvAsset, 0); break; default: break; } // Load adjustment data, if any try { PHAdjustmentData adjustmentData = contentEditingInput.AdjustmentData; if (adjustmentData != null) { selectedFilterName = (string)(NSString)NSKeyedUnarchiver.UnarchiveObject(adjustmentData.Data); } } catch (Exception exception) { Console.WriteLine("Exception decoding adjustment data: {0}", exception); } if (string.IsNullOrWhiteSpace(selectedFilterName)) { selectedFilterName = "CISepiaTone"; } initialFilterName = selectedFilterName; // Update filter and background image UpdateFilter(); UpdateFilterPreview(); BackgroundImageView.Image = placeholderImage; }
FavoritesManager() { var userDefaults = NSUserDefaults.StandardUserDefaults; var mapData = userDefaults.DataForKey(accessoryToCharacteristicIdentifierMappingKey); if (mapData != null) { var rawDictionary = NSKeyedUnarchiver.UnarchiveObject(mapData) as NSDictionary; if (rawDictionary != null) { foreach (var kvp in rawDictionary) { accessoryToCharacteristicIdentifiers [(NSUuid)kvp.Key] = new List <NSUuid> (NSArray.FromArray <NSUuid> ((NSArray)kvp.Value)); } } } }
public override bool AcceptDrop(NSTableView tableView, NSDraggingInfo info, nint row, NSTableViewDropOperation dropOperation) { NSData data = info.DraggingPasteboard.GetDataForType(DataTypeName); NSIndexSet indexes = NSKeyedUnarchiver.UnarchiveObject(data) as NSIndexSet; if (indexes == null) { return(false); } // Dropping at the bottom gives a row at the count, but we shift indexes first if (row >= this.viewModel.Targets.Count) { row = this.viewModel.Targets.Count - 1; } this.viewModel.MoveTarget((int)indexes.FirstIndex, (int)row); return(true); }
// // Load support: // Override one of ReadFromData, ReadFromFileWrapper or ReadFromUrl // public override bool ReadFromData(NSData data, string typeName, out NSError outError) { outError = null; Console.WriteLine("About to read data of type {0}", typeName); NSMutableArray newArray = null; try { newArray = (NSMutableArray)NSKeyedUnarchiver.UnarchiveObject(data); } catch (Exception ex) { Console.WriteLine("Error loading file: Exception: {0}", ex.Message); NSDictionary d = NSDictionary.FromObjectAndKey(new NSString(NSBundle.MainBundle.LocalizedString("DATA_CORRUPTED", null)), NSError.LocalizedFailureReasonErrorKey); outError = NSError.FromDomain(NSError.OsStatusErrorDomain, -4, d); return(false); } Ovals = NSArray.FromArray <Oval>(newArray).ToList <Oval>(); return(true); }
public static void RegisterOverrideClasses(NSKeyedUnarchiver unarchiver, PSPDFDocument document) { _RegisterOverrideClasses (unarchiver.Handle, document.Handle); }
public static void AnnotationSupportLegacyFormat(NSKeyedUnarchiver unarchiver) { _AnnotationSupportLegacyFormat (unarchiver.Handle); }