// NSURLConnection delegates (generally we pass these on to our client)

        public override NSUrlRequest WillSendRequest(NSUrlConnection connection, NSUrlRequest request, NSUrlResponse response)
        {
            // Thanks to Nick Dowell https://gist.github.com/1885821
            if (response != null)
            {
                var redirectableRequest = Request.MutableCopy as NSMutableUrlRequest;

                // We need to remove our header so we know to handle this request and cache it.
                // There are 3 requests in flight: the outside request, which we handled, the internal request,
                // which we marked with our header, and the redirectableRequest, which we're modifying here.
                // The redirectable request will cause a new outside request from the NSURLProtocolClient, which
                // must not be marked with our header.
                redirectableRequest.SetValueForKey(null, MtRnCachingUrlHeader);

                var cachePath = CachePathForRequest(this.Request);
                var cache     = new MtRnCachedData();
                cache.Response        = response;
                cache.Data            = this.Data;
                cache.RedirectRequest = redirectableRequest;
                NSKeyedArchiver.ArchiveRootObjectToFile(cache, cachePath);
                this.Client.Redirected(this, redirectableRequest, response);
                return(redirectableRequest);
            }
            else
            {
                return(request);
            }
        }
Ejemplo n.º 2
0
        public int Begin(NSIndexSet aIndices, object aSource, NSPasteboard aPasteboard)
        {
            // build list of indices to be dragged
            List <int> indices = new List <int>();

            uint index = aIndices.FirstIndex;

            while (index != FoundationFramework.NSNotFound)
            {
                indices.Add((int)index);
                index = aIndices.IndexGreaterThanIndex(index);
            }

            // set the current data to be dragged
            DragDropManager.Current = iController.DragBegin(indices, aSource);

            // add a token to the pasteboard
            PasteboardViewDragData token = new PasteboardViewDragData();
            NSData tokenData             = NSKeyedArchiver.ArchivedDataWithRootObject(token);

            token.Release();

            aPasteboard.DeclareTypesOwner(NSArray.ArrayWithObject(PasteboardViewDragData.PboardType), null);
            aPasteboard.SetDataForType(tokenData, PasteboardViewDragData.PboardType);

            return(indices.Count);
        }
Ejemplo n.º 3
0
        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);
                }
            }
        }
Ejemplo n.º 4
0
        public static bool Send(NSDictionary <NSString, NSObject> dataToSend)
        {
            if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
            {
                UIPasteboard.General.SetItems(new NSDictionary <NSString, NSObject>[] { dataToSend }, new UIPasteboardOptions
                {
                    LocalOnly      = true,
                    ExpirationDate = NSDate.FromTimeIntervalSinceNow(PASTEBOARD_EXPIRATION_SECONDS)
                });
            }
            else
            {
                UIPasteboard.General.SetData(NSKeyedArchiver.ArchivedDataWithRootObject(dataToSend), PASTEBOARD_STICKER_PACK_DATA_TYPE);
            }

            DispatchQueue.MainQueue.DispatchAsync(() =>
            {
                if (CanSend())
                {
                    if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
                    {
                        UIApplication.SharedApplication.OpenUrl(new NSUrl(WHATSAPP_URL), new NSDictionary(), null);
                    }
                    else
                    {
                        UIApplication.SharedApplication.OpenUrl(new NSUrl(WHATSAPP_URL));
                    }
                }
            });
            return(true);
        }
Ejemplo n.º 5
0
        public bool TableViewWriteToPasteboard(NSTableView aTableView, NSIndexSet aRows, NSPasteboard aPasteboard)
        {
            Console.WriteLine("TableViewWriteToPasteboard::" + aRows.Count);

            iDraggedBookmarks = new List <Bookmark>();

            uint index = aRows.FirstIndex;

            while (index != FoundationFramework.NSNotFound)
            {
                iDraggedBookmarks.Add(iBookmarks[(int)index].CastAs <BookmarkData>().Bookmark);
                index = aRows.IndexGreaterThanIndex(index);
            }


            // add a token to the pasteboard
            PasteboardViewDragDataBookmarks token = new PasteboardViewDragDataBookmarks();
            NSData tokenData = NSKeyedArchiver.ArchivedDataWithRootObject(token);

            token.Release();

            aPasteboard.DeclareTypesOwner(NSArray.ArrayWithObject(PasteboardViewDragDataBookmarks.PboardType), null);
            aPasteboard.SetDataForType(tokenData, PasteboardViewDragDataBookmarks.PboardType);
            iDragging = true;
            return(true);
        }
Ejemplo n.º 6
0
        public void save()
        {
            NSData data = NSKeyedArchiver.archivedDataWithRootObject(this.tasks);

            data.writeToFile(_dataFileName) atomically(true);
            NSLog("Data has been saved to local file (%@)", _dataFileName);
        }
Ejemplo n.º 7
0
        public void Encode()
        {
            IntPtr nscoding = Runtime.GetProtocol("NSCoding");

            Assert.That(nscoding, Is.Not.EqualTo(IntPtr.Zero), "NSCoding");

#if !XAMCORE_2_0
            // NSObject does not conform to NSCoding
            using (var o = new NSObject()) {
                Assert.False(o.ConformsToProtocol(nscoding), "NSObject/NSCoding");
                using (var c = new NSCoder()) {
                    Assert.Throws <InvalidOperationException> (delegate {
                        o.EncodeTo(c);
                    }, "NSObject/!NSCoding");
                }
            }
#endif

            // NSNumber conforms to NSCoding
            using (var n = new NSNumber(-1)) {
                Assert.True(n.ConformsToProtocol(nscoding), "NSNumber/NSCoding");
                using (var d = new NSMutableData())
                    using (var a = new NSKeyedArchiver(d)) {
                        n.EncodeTo(a);
                        a.FinishEncoding();
                    }
            }
        }
Ejemplo n.º 8
0
        public override void DidEnterBackground(UIApplication application)
        {
            var       subViews = mapViewController.View.Subviews;
            MKMapView mapView  = subViews[0] as MKMapView;

            Console.WriteLine("mapView: {0}", mapView);
            var            tempArray   = mapView.Annotations;
            NSMutableArray annotations = new NSMutableArray();

            Console.WriteLine("tempArray: {0}", tempArray.ToString());
            for (int i = 0; i < tempArray.Length; i++)
            {
                if (tempArray[i].GetType() == typeof(MKUserLocation))
                {
                    Console.WriteLine("MKUserLocation: {0}", tempArray[i]);
                }
                else
                {
                    Console.WriteLine("MKMapPoint added: {0}", tempArray[i]);
                    annotations.Add(tempArray[i]);
                }
            }
            var    documentDirectories = NSSearchPath.GetDirectories(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User, true);
            string documentDirectory   = documentDirectories[0];
            string path = Path.Combine(documentDirectory, "annotations.archive");

            Console.WriteLine("Path: {0}", path);
            bool success = NSKeyedArchiver.ArchiveRootObjectToFile(annotations, path);

            if (success)
            {
                Console.WriteLine("Saved Annotations {0}", annotations.ToString());
            }
        }
Ejemplo n.º 9
0
        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 []");
        }
Ejemplo n.º 10
0
        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 override bool WriteRows(NSTableView tableView, NSIndexSet rowIndexes, NSPasteboard pboard)
            {
                var item = new NSPasteboardItem();

                item.SetDataForType(NSKeyedArchiver.ArchivedDataWithRootObject(rowIndexes), DataTypeName);
                pboard.WriteObjects(new[] { item });
                return(true);
            }
Ejemplo n.º 12
0
        // Overrides required for drag and drop

        public override bool WriteRows(NSTableView tableView, Foundation.NSIndexSet rowIndexes, NSPasteboard pboard)
        {
            NSData data = NSKeyedArchiver.ArchivedDataWithRootObject(rowIndexes);

            pboard.DeclareTypes(new string[] { DungeonToolsConstants.ECOUNTER_INITIATIVE_DRAG_DROP_TYPE }, this);
            pboard.SetDataForType(data, DungeonToolsConstants.ECOUNTER_INITIATIVE_DRAG_DROP_TYPE);
            return(true);
        }
Ejemplo n.º 13
0
        public void AddWidgetTrackingEvent(WidgetTrackingEvent e)
        {
            var currentEvents = (NSMutableArray)getTrackableEvents(widgetInstalledKey).MutableCopy();

            currentEvents.Add(e);

            userDefaults[siriTrackingEventsKey] = NSKeyedArchiver.ArchivedDataWithRootObject(currentEvents);
            userDefaults.Synchronize();
        }
Ejemplo n.º 14
0
        //
        // Save support:
        //    Override one of GetAsData, GetAsFileWrapper, or WriteToUrl.
        //

        // This method should store the contents of the document using the given typeName
        // on the return NSData value.
        public override NSData GetAsData(string documentType, out NSError outError)
        {
            outError = null;
            // End editing
            tableView.Window.EndEditingFor(null);

            // Create an NSData object from the cars array
            return(NSKeyedArchiver.ArchivedDataWithRootObject(Cars));
        }
Ejemplo n.º 15
0
        async partial void SaveExperience()
        {
            var worldMap = await _sceneView.Session.GetCurrentWorldMapAsync();

            if (worldMap != null)
            {
                try
                {
                    // Add a snapshot image indicating where the map was captured.
                    var snapshotAnchor = SnapshotAnchor.Create(_sceneView);

                    if (snapshotAnchor != null)
                    {
                        var imageView = UIImage.LoadFromData(snapshotAnchor.ImageData);
                        _snapShotThumbnail.Hidden = false;
                        _snapShotThumbnail.Image  = imageView;
                        worldMap.Anchors          = worldMap.Anchors.Append(snapshotAnchor).ToArray();
                        Debug.WriteLine("Screenshot saved");
                    }
                    else
                    {
                        Debug.WriteLine("Snapshot anchor is null");
                    }
                }
                catch
                {
                    Debug.WriteLine("Can't take screenshot");
                    throw;
                }

                var data = NSKeyedArchiver.ArchivedDataWithRootObject(worldMap, true, out var err);

                if (err != null)
                {
                    Debug.WriteLine(err);
                    return;
                }

                try
                {
                    File.WriteAllBytes(MapSaveURL, data.ToArray());
                    DispatchQueue.MainQueue.DispatchAsync(() =>
                    {
                        _loadButton.Hidden  = false;
                        _loadButton.Enabled = true;
                    });
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"Can't save map: {ex.Message}");
                }
            }
            else
            {
                Debug.WriteLine("Can't get current world map");
            }
        }
Ejemplo n.º 16
0
        private NSDataItem(IMimeItem item)
        {
            var nsObject = item.Value.ToNSObject();

            if (nsObject != null)
            {
                NSUti         = item.ToNsUti();
                KeyedArchiver = NSKeyedArchiver.ArchivedDataWithRootObject(nsObject);
            }
        }
Ejemplo n.º 17
0
        public override bool WriteRows(NSTableView tableView, NSIndexSet rowIndexes, NSPasteboard pboard)
        {
            // Copy the row numbers to the pasteboard.
            NSData zNSIndexSetData = NSKeyedArchiver.ArchivedDataWithRootObject(rowIndexes);

            string[] typeArray = { "NSStringPboardType" };
            pboard.DeclareTypes(typeArray, this);
            pboard.SetDataForType(zNSIndexSetData, "NSStringPboardType");
            return(true);
        }
Ejemplo n.º 18
0
        public void sendMessage(NSString msg)
        {
            NSDictionary    message  = NSDictionary.FromObjectAndKey(msg, new NSString("msg"));
            NSMutableData   data     = new NSMutableData();
            NSKeyedArchiver archiver = new NSKeyedArchiver(data);

            archiver.Encode(message);
            archiver.FinishEncoding();
            ShowKit.ShowKit.SendMessage(data);
        }
        private void SaveDocumentInDevice(DocumentArchive doc)
        {
            this.DocumentsDownloadedList.Add(doc);

            // Archiver document object
            NSData encodedObject = NSKeyedArchiver.ArchivedDataWithRootObject(this.DocumentsDownloadedList);

            NSUserDefaults.StandardUserDefaults.SetValueForKey(encodedObject, DocumentSavedKey);
            NSUserDefaults.StandardUserDefaults.Synchronize();
        }
 public NSObject GetPasteboardPropertyListForType(string type)
 {
     if (type == _pasteboardItemName)
     {
         return(NSKeyedArchiver.ArchivedDataWithRootObject(this));
     }
     else
     {
         return(null);
     }
 }
Ejemplo n.º 21
0
        //Save stored scores to file
        public void writeStoredScore()
        {
            NSError err;
            NSData  archivedScore = NSKeyedArchiver.ArchivedDataWithRootObject(storedScores);

            archivedScore.Save(this.storedScoresFilename, NSDataWritingOptions.FileProtectionNone, out err);
            if (err != null)
            {
                Console.WriteLine("Error when saving stored scores.");
            }
        }
Ejemplo n.º 22
0
        // First, cleans out the internal identifier structures, then saves
        // the `accessoryToCharacteristicIdentifiers` map and `accessoryIdentifiers` array into `NSUserDefaults`.
        // This method should be called whenever a change is made to the internal structures.
        void Save()
        {
            RemoveUnusedIdentifiers();

            var userDefaults = NSUserDefaults.StandardUserDefaults;

            NSDictionary nativeMap = Convert(accessoryToCharacteristicIdentifiers);
            var          mapData   = NSKeyedArchiver.ArchivedDataWithRootObject(nativeMap);

            userDefaults [accessoryToCharacteristicIdentifierMappingKey] = mapData;
        }
        /// <summary>
        /// Stores the provided video codec setting into the store.
        /// If the provided video codec is not part of the available video codecs
        /// the store operation will not be executed and NO will be returned.
        /// </summary>
        /// <param name="videoCodec">video codec settings the string to be stored.</param>
        /// <returns>YES/NO depending on success.</returns>
        public bool StoreVideoCodecSetting(RTCVideoCodecInfo videoCodec)
        {
            if (!AvailableVideoCodecs.Contains(videoCodec))
            {
                return(false);
            }
            var codecData = NSKeyedArchiver.ArchivedDataWithRootObject(videoCodec);

            _settingStore.VideoCodec = codecData;
            return(true);
        }
Ejemplo n.º 24
0
        //
        // Save support:
        //    Override one of GetAsData, GetAsFileWrapper, or WriteToUrl.
        //

        // This method should store the contents of the document using the given typeName
        // on the return NSData value.
        public override NSData GetAsData(string documentType, out NSError outError)
        {
            outError = null;
            // End editing
            tableView.Window.EndEditingFor(null);

            // Create an NSData object from the employees array
            return(NSKeyedArchiver.ArchivedDataWithRootObject(Employees));

            // Default template code
//			outError = NSError.FromDomain(NSError.OsStatusErrorDomain, -4);
//			return null;
        }
 // Saves the OIDAuthState to NSUSerDefaults.
 private void SaveState()
 {
     // for production usage consider using the OS Keychain instead
     if (AuthState != null)
     {
         var archivedAuthState = NSKeyedArchiver.ArchivedDataWithRootObject(AuthState);
         NSUserDefaults.StandardUserDefaults[kAppAuthExampleAuthStateKey] = archivedAuthState;
     }
     else
     {
         NSUserDefaults.StandardUserDefaults.RemoveObject(kAppAuthExampleAuthStateKey);
     }
     NSUserDefaults.StandardUserDefaults.Synchronize();
 }
        public override void FinishedLoading(NSUrlConnection connection)
        {
            Client.FinishedLoading(this);

            var cachePath = CachePathForRequest(this.Request);
            var cache     = new MtRnCachedData();

            cache.Response = this.Response;
            cache.Data     = this.Data;
            NSKeyedArchiver.ArchiveRootObjectToFile(cache, cachePath);

            Connection = null;
            Data       = null;
            Response   = null;
        }
Ejemplo n.º 27
0
        //
        // Save support:
        //    Override one of GetAsData, GetAsFileWrapper, or WriteToUrl.
        //

        // This method should store the contents of the document using the given typeName
        // on the return NSData value.
        public override NSData GetAsData(string documentType, out NSError outError)
        {
            outError = null;
            NSMutableArray array = new NSMutableArray();

            foreach (Oval o in Ovals)
            {
                array.Add(o);
            }

            // Create an NSData object from the employees array
            NSData data = NSKeyedArchiver.ArchivedDataWithRootObject(array);

            return(data);
        }
Ejemplo n.º 28
0
        public virtual NSObject GetPasteboardPropertyListForType(string type)
        {
            // Take action based on the requested type
            switch (type)
            {
            case "com.xamarin.image-info":
                return(NSKeyedArchiver.ArchivedDataWithRootObject(this));

            case "public.text":
                return(new NSString(string.Format("{0}.{1}", Name, ImageType)));
            }

            // Failure, return null
            return(null);
        }
Ejemplo n.º 29
0
		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");
				}
			}
		}
Ejemplo n.º 30
0
        public void Encode()
        {
            IntPtr nscoding = Runtime.GetProtocol("NSCoding");

            Assert.That(nscoding, Is.Not.EqualTo(IntPtr.Zero), "NSCoding");

            // NSNumber conforms to NSCoding
            using (var n = new NSNumber(-1)) {
                Assert.True(n.ConformsToProtocol(nscoding), "NSNumber/NSCoding");
                using (var d = new NSMutableData())
                    using (var a = new NSKeyedArchiver(d)) {
                        n.EncodeTo(a);
                        a.FinishEncoding();
                    }
            }
        }