Example #1
0
			public override void ReceivedData (NSUrlConnection connection, NSData data)
			{
				if (_view.imageData==null)
					_view.imageData = new NSMutableData();

				_view.imageData.AppendData(data);	
			}
        public override void Clicked(UIActionSheet actionview, int buttonIndex)
        {
            if (buttonIndex == 0)
            {
                Console.Write("Satya!!!!!!");

                /*UIActivityIndicatorView spinner = new UIActivityIndicatorView(new RectangleF(0,0,200,300));
                spinner.ActivityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge;
                spinner.Center= new PointF(160, 140);
                spinner.HidesWhenStopped = true;
                actionview.AddSubview(spinner);
                InvokeOnMainThread(delegate() {
                    spinner.StartAnimating();
                });

                */

                var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);

                fileName = documents + "/" + fileName;

                data = NSData.FromUrl(_nsurl);
                File.WriteAllBytes(fileName,data.ToArray());

                if (File.Exists(fileName))
                {
                    UIAlertView alert = new UIAlertView();
                    alert.Title = "Download Complete";
                    alert.AddButton("Done");
                    alert.Show();
                }
                    //spinner.StopAnimating();

            }
        }
Example #3
0
 public override void RegisteredForRemoteNotifications (UIApplication application, NSData deviceToken)
 {
     Task.Run (async () => {
         var service = ServiceContainer.Resolve<APNSManager> ();
         await service.RegisteredForRemoteNotificationsAsync (application, deviceToken);
     });
 }
        public void OnRegisteredSuccess(NSData token)
        {
            Debug.WriteLine("{0} - Succesfully Registered.", PushNotificationKey.DomainName);

            string trimmedDeviceToken =token.Description;
            if (!string.IsNullOrWhiteSpace(trimmedDeviceToken))
            {
                trimmedDeviceToken = trimmedDeviceToken.Trim('<');
                trimmedDeviceToken = trimmedDeviceToken.Trim('>');
                trimmedDeviceToken = trimmedDeviceToken.Trim();
                trimmedDeviceToken = trimmedDeviceToken.Replace(" ","");
            }
            Console.WriteLine("{0} - Token: {1}", PushNotificationKey.DomainName, trimmedDeviceToken);

            if (CrossPushNotification.IsInitialized)
            {
                CrossPushNotification.PushNotificationListener.OnRegistered(trimmedDeviceToken, DeviceType.iOS);
            }
            else
            {
                throw NewPushNotificationNotInitializedException();
            }

            NSUserDefaults.StandardUserDefaults.SetString(trimmedDeviceToken, PushNotificationKey.Token);
            NSUserDefaults.StandardUserDefaults.Synchronize ();
        }
Example #5
0
		// Collect all the data
		public override void ReceivedData (NSUrlConnection connection, NSData data)
		{
			byte [] nb = new byte [result.Length + data.Length];
			result.CopyTo (nb, 0);
			Marshal.Copy (data.Bytes, nb, result.Length, (int) data.Length);
			result = nb;
		}
Example #6
0
        public async override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
        {
            this.deviceToken = deviceToken.ToString().Replace("<", "").Replace(">", "").Replace(" ", "");

            var push = CommonAppSettings.MobileService.GetPush();
            var employeeId = CommonAppSettings.FixedEmployeeId;

            try
            {
                var jsonTemplate = "{\"aps\":{\"message\":\"$(message)\"}}";
                var expiry = DateTime.Now.AddDays(90).ToString(CultureInfo.CreateSpecificCulture("en-US"));

                await push.RegisterTemplateAsync(this.deviceToken, jsonTemplate, expiry, "MyShuttleTemplate",
                    new string[] 
                    { 
                        string.Format("VehicleApproved-{0}", employeeId),
                        string.Format("VehicleRejected-{0}", employeeId),
                        string.Format("VehicleArrived-{0}", employeeId)
                    });
            }
            catch (Exception e)
            {
                var userInteractionService = Mvx.Resolve<IUserInteraction>();

                if (userInteractionService != null)
                {
                    userInteractionService.Alert(e.Message, title: "Error registering notifications");
                }
            }
        }
		public async override void RegisteredForRemoteNotifications (UIApplication application, NSData deviceToken)
		{
			ParseInstallation installation = ParseInstallation.CurrentInstallation;
			installation.SetDeviceTokenFromData (deviceToken);
			await ParsePush.SubscribeAsync ("");
			await installation.SaveAsync ();
		}
Example #8
0
 public CWNetwork[] ScanForNetworksWithSsid(NSData ssid, out NSError error)
 {
     NSSet networks = _ScanForNetworksWithSsid (ssid, out error);
     if (networks != null)
         return networks.ToArray<CWNetwork> ();
     return null;
 }
 public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
 {
     if (CrossPushNotification.Current is IPushNotificationHandler)
     {
         ((IPushNotificationHandler)CrossPushNotification.Current).OnRegisteredSuccess(deviceToken);
     }
 }
        /// <summary>
        /// We succeeded in registering for notifications
        /// </summary>
        /// <param name="application"></param>
        /// <param name="deviceToken"></param>
        public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
        {
            // Get current device token
            var deviceTokenDesc = deviceToken.Description;
            if (!string.IsNullOrWhiteSpace(deviceTokenDesc))
            {
                deviceTokenDesc = deviceTokenDesc.Trim('<').Trim('>').Replace(" ", "");
            }

            UserDialogs.Instance.Alert(deviceTokenDesc);

            // Has the token changed?
            if (!string.IsNullOrEmpty(deviceTokenDesc))
            {
                //Register the user on your server
                DeviceToken apiToken = new DeviceToken
                {
                    Token = deviceTokenDesc,
                    Device = Device.OS.ToString()
                };
                ApiService apiService = new ApiService();
                apiService.PostAsync<DeviceToken>("Devices/Post", apiToken);

            }
        }
Example #11
0
        public SecCertificate(NSData data)
        {
            if (data == null)
                throw new ArgumentNullException ("data");

            Initialize (data);
        }
		public void DidFinishProcessingPhoto (AVCapturePhotoOutput captureOutput, CMSampleBuffer photoSampleBuffer, CMSampleBuffer previewPhotoSampleBuffer, AVCaptureResolvedPhotoSettings resolvedSettings, AVCaptureBracketedStillImageSettings bracketSettings, NSError error)
		{
			if (photoSampleBuffer != null)
				photoData = AVCapturePhotoOutput.GetJpegPhotoDataRepresentation (photoSampleBuffer, previewPhotoSampleBuffer);
			else
				Console.WriteLine ($"Error capturing photo: {error.LocalizedDescription}");
		}
Example #13
0
		public CGEvent (NSData source) 
		{
			if (source == null)
				throw new ArgumentNullException ("source");

			handle = CGEventCreateFromData (IntPtr.Zero, source.Handle);
		}
 public override void RegisteredForRemoteNotifications(
   UIApplication application, NSData deviceToken)
 {
     DonkyiOS.RegisteredForRemoteNotifications(
     application,
     deviceToken);
 }
Example #15
0
		protected override void Dispose (bool disposing)
		{
			if (data != null) {
				data.Dispose ();
				data = null;
			}
		}
        public override UITableViewCell GetCell(UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
        {

            SkatersTableCell cell = tableView.DequeueReusableCell(cellIdentifier) as SkatersTableCell;
            try
            {
                if (cell == null)
                    cell = new SkatersTableCell(cellIdentifier);
                NSData data = new NSData();
                if (!String.IsNullOrEmpty(tableItems[indexPath.Row].ThumbUrl))
                {
                    NSUrl nsUrl = new NSUrl(tableItems[indexPath.Row].ThumbUrl);
                    data = NSData.FromUrl(nsUrl);
                }
                cell.UpdateCell(tableItems[indexPath.Row].DerbyName, tableItems[indexPath.Row].DerbyNumber, new UIImage(data));
                OnGotCell();
                CellOn = indexPath.Row;
            }
            catch (Exception exception)
            {
                ErrorHandler.Save(exception, MobileTypeEnum.iPhone);
            }
            return cell;

        }
        public override UITableViewCell GetCell(UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
        {

            ImageTableCell cell = tableView.DequeueReusableCell(cellIdentifier) as ImageTableCell;
            try
            {
                if (cell == null)
                    cell = new ImageTableCell(cellIdentifier, navigate.View.Bounds.Width);
                NSData data = new NSData();
                if (!String.IsNullOrEmpty(_urls[indexPath.Row]))
                {
                    NSUrl nsUrl = new NSUrl(_urls[indexPath.Row]);
                    data = NSData.FromUrl(nsUrl);
                }
                cell.UpdateCell(new UIImage(data));
                
                OnGotCell();
                CellOn = indexPath.Row;
            }
            catch (Exception exception)
            {
                ErrorHandler.Save(exception, MobileTypeEnum.iPhone);
            }
            return cell;

        }
Example #18
0
 public static NSString FromData(NSData data, NSStringEncoding encoding)
 {
     // Allocate a string, do not init
     IntPtr h = Messaging.IntPtr_objc_msgSend (Class.GetHandle ("NSString"), Selector.Alloc);
     h = Messaging.IntPtr_objc_msgSend_IntPtr_int (h, selInitWithDataEncoding, data.Handle, (int)encoding);
     return new NSString (h);
 }
Example #19
0
 public static SecurityResult CopyMatching(NSDictionary query, ref NSData result)
 {
     IntPtr handle = IntPtr.Zero;
     SecurityResult osStatus = (SecurityResult)SecItemCopyMatching(query.Handle, ref handle);
     if (osStatus == SecurityResult.Success)
         result = new NSData(handle);
     return osStatus;
 }
		public NSData CopyData ()
		{
			var provider = CGDataProviderCopyData (handle);
			var data = new NSData (provider);

			CGDataProviderRelease (provider);
			return data;
		}
Example #21
0
 private void OnStatusUpdate(NSData data)
 {
     UserStatuses status;
     if (Enum.TryParse(GetStringFromNSData(data), out status))
     {
         User.Status = status;
     }
 }
 public override void RegisteredForRemoteNotifications(UIApplication application, NSData token)
 {
     var deviceToken = token.Description.Replace("<", "").Replace(">", "").Replace(" ", "");
     if (!string.IsNullOrEmpty(deviceToken))
     {
         SNSUtils.RegisterDevice(SNSUtils.Platform.IOS, deviceToken);
     }
 }
 protected override void Dispose(bool disposing)
 {
     if (theData != null)
     {
         theData.Dispose();
         theData = null;
     }
 }
        internal static string ParseDeviceToken(NSData deviceToken)
        {
            if (deviceToken == null)
            {
                throw new ArgumentNullException("deviceToken");
            }

            return TrimDeviceToken(deviceToken.Description);
        }
 public override void ReceivedData(NSUrlConnection connection, NSData data)
 {
     if (this.tempData == null)
     {
         this.tempData = new NSMutableData();
     }
     
     this.tempData.AppendData(data);
 }
		public async override void RegisteredForRemoteNotifications (UIApplication application, NSData deviceToken)
		{
			try {
				NativeRegistration = await Hub.RegisterNativeAsync(deviceToken);
				new UIAlertView("Notification Hub Registration", "Registration ID: " + NativeRegistration.RegistrationId, null, "OK", null).Show();
			} catch (Exception ex) {
				new UIAlertView("Error registering push notifications", ex.Message, null, "OK", null).Show();
			}
		}
Example #27
0
        public CGImageMetadata(NSData data)
        {
            if (data == null)
                throw new ArgumentNullException ("data");

            Handle = CGImageMetadataCreateFromXMPData (data.Handle);
            if (Handle == IntPtr.Zero)
                throw new ArgumentException ("data");
        }
Example #28
0
        public SecCertificate(NSData data)
        {
            if (data == null)
                throw new ArgumentNullException ("data");

            handle = SecCertificateCreateWithData (IntPtr.Zero, data.Handle);
            if (handle == IntPtr.Zero)
                throw new ArgumentException ("Not a valid DER-encoded X.509 certificate");
        }
Example #29
0
		public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
		{
			string trimmedDeviceToken = deviceToken.Description;
			if (!string.IsNullOrWhiteSpace(trimmedDeviceToken))
			{
				trimmedDeviceToken = trimmedDeviceToken.Trim('<');
				trimmedDeviceToken = trimmedDeviceToken.Trim('>');
			}
			DeviceToken = trimmedDeviceToken;
		}
Example #30
0
        public static AVAudioPlayer FromData(NSData data)
        {
            unsafe {
                var ap = new AVAudioPlayer (data, IntPtr.Zero);
                if (ap.Handle == IntPtr.Zero)
                    return null;

                return ap;
            }
        }
Example #31
0
        public void Create(Stream stream)
        {
            var data = NSData.FromStream(stream);

            Control = new NSImage(data);
        }
Example #32
0
        public override async void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
        {
            string deviceTokenStr = deviceToken.ToString();

            Console.WriteLine(deviceTokenStr);

            bool deviceTokenAlreadyRegistered = string.Compare(deviceTokenStr, Awpbs.Mobile.App.KeyChain.RegisteredDeviceToken, false) == 0;

            if (deviceTokenAlreadyRegistered == false)
            {
                if (App.LoginAndRegistrationLogic.RegistrationStatus == RegistrationStatusEnum.Registered)
                {
                    // already logged-in as a user -> register the device token
                    if (await App.WebService.RegisterDeviceToken(deviceTokenStr, true, false) == true)
                    {
                        Awpbs.Mobile.App.KeyChain.RegisteredDeviceToken = deviceTokenStr;
                    }
                }
                else
                {
                    // not yet logged-in as a user -> register the device token once logged-in
                    Awpbs.Mobile.App.KeyChain.DeviceTokenToRegisterWhenLoggedIn = deviceTokenStr;
                }
            }

            // https://www.youtube.com/watch?v=m2txoLvosVw
            // https://mallibone.com/post/xamarin.ios-push-notifications-through-azure-push-notifications
        }
        private void HandleStreamingContentKeyRequest(AVContentKeyRequest keyRequest)
        {
            var contentKeyIdentifierString = keyRequest.Identifier.ToString();

            if (string.IsNullOrEmpty(contentKeyIdentifierString))
            {
                Debug.WriteLine("Failed to retrieve the assetID from the keyRequest!");
                return;
            }

            var contentKeyIdentifierUrl = new NSUrl(contentKeyIdentifierString);
            var assetIdString           = contentKeyIdentifierUrl.Host;
            var assetIdData             = NSData.FromString(assetIdString, NSStringEncoding.UTF8);

            Action provideOnlineKey = () =>
            {
                var applicationCertificate = RequestApplicationCertificate();

                try
                {
                    var keys    = new[] { new NSString(AVContentKeyRequest.ProtocolVersions) };
                    var numbers = new NSMutableArray <NSNumber>();
                    numbers.Add(new NSNumber(1));
                    var objects = new NSObject[] { numbers };
                    var options = new NSDictionary <NSString, NSObject>(keys, objects);
                    keyRequest.MakeStreamingContentKeyRequestData(applicationCertificate, assetIdData, options, async(data, error) => {
                        var ckcData = await this.RequestContentKeyFromKeySecurityModule(data, assetIdString);

                        if (ckcData == null)
                        {
                            return;
                        }

                        var keyResponse = AVContentKeyResponse.Create(ckcData);

                        keyRequest.Process(keyResponse);
                    });
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"Failed to make streaming content key request data: {ex.Message}");
                }
            };

            /*
             * When you receive an AVContentKeyRequest via -contentKeySession:didProvideContentKeyRequest:
             * and you want the resulting key response to produce a key that can persist across multiple
             * playback sessions, you must invoke -respondByRequestingPersistableContentKeyRequest on that
             * AVContentKeyRequest in order to signal that you want to process an AVPersistableContentKeyRequest
             * instead. If the underlying protocol supports persistable content keys, in response your
             * delegate will receive an AVPersistableContentKeyRequest via -contentKeySession:didProvidePersistableContentKeyRequest:.
             */
            if (ShouldRequestPersistableContentKey(assetIdString) || PersistableContentKeyExistsOnDisk(assetIdString))
            {
                try
                {
                    NSError error;
                    keyRequest.RespondByRequestingPersistableContentKeyRequest(out error);

                    if (error != null)
                    {
                        throw new Exception($"Error requesting persistable content key: {error.ToString()}");
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);

                    /*
                     * This case will occur when the client gets a key loading request from an AirPlay Session.
                     * You should answer the key request using an online key from your key server.
                     */
                    provideOnlineKey();
                }

                return;
            }

            try
            {
                provideOnlineKey();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
 static UIImage FromUrl(string uri)
 {
     using (var url = new NSUrl(uri))
         using (var data = NSData.FromUrl(url))
             return(UIImage.LoadFromData(data));
 }
Example #35
0
 public override NSUrlSessionDownloadTask CreateDownloadTaskFromResumeData(NSData resumeData, NSUrlDownloadSessionResponse completionHandler)
 {
     throw new NotImplementedException();
 }
Example #36
0
 public NSDataStream(NSData data)
 {
     this.theData = data;
 }
 public virtual bool AddCachedImage(NSData imageData, string name)
 {
     throw new PlatformNotSupportedException(Constants.WatchKitRemoved);
 }
Example #38
0
            public override void DidReceiveData(NSUrlSession session, NSUrlSessionDataTask dataTask, NSData data)
            {
                var inflight = GetInflightData(dataTask);

                if (inflight == null)
                {
                    return;
                }

                inflight.Stream.Add(data);
                SetResponse(inflight);
            }
Example #39
0
        public void AddConfig()
        {
            // The password for the VPN connection, add this to Keychain
            var password = new SecRecord(SecKind.GenericPassword)
            {
                Service   = "Password Service",
                ValueData = NSData.FromString("MY_PASSWORD", NSStringEncoding.UTF8),
                Generic   = NSData.FromString("VPNPas", NSStringEncoding.UTF8),
            };

            // The query for the VPN password. Use this to find the password in Keychain
            var queryPassword = new SecRecord(SecKind.GenericPassword)
            {
                Service = "Password Service",
                Generic = NSData.FromString("VPNPas", NSStringEncoding.UTF8),
            };

            // The shared secret for the VPN connection, add this to Keychain
            var secret = new SecRecord(SecKind.GenericPassword)
            {
                Service   = "Secret Service",
                ValueData = NSData.FromString("hide.io", NSStringEncoding.UTF8),
                Generic   = NSData.FromString("secret", NSStringEncoding.UTF8),
            };

            // The query for the VPN shared secret. Use this to find the shared secret in Keychain
            var querySecret = new SecRecord(SecKind.GenericPassword)
            {
                Service = "Secret Service",
                Generic = NSData.FromString("secret", NSStringEncoding.UTF8),
            };

            // First remove old Keychain entries, then add the new ones
            // Just for testing purposes: this is to make sure the keychain entries are correct
            var err = SecKeyChain.Remove(queryPassword);

            Console.WriteLine("Password remove: " + err);

            err = SecKeyChain.Remove(querySecret);
            Console.WriteLine("Secret remove: " + err);

            err = SecKeyChain.Add(password);
            Console.WriteLine("Password add: " + err);

            err = SecKeyChain.Add(secret);
            Console.WriteLine("Secret add: " + err);


            manager.LoadFromPreferences(error => {
                if (error != null)
                {
                    Console.WriteLine("Error loading preferences: ");
                    Console.WriteLine(error);
                }
                else
                {
                    NEVpnProtocol p = null;

                    // IKEv2 Protocol
                    NEVpnProtocolIke2 ike2    = new NEVpnProtocolIke2();
                    ike2.AuthenticationMethod = NEVpnIkeAuthenticationMethod.None;
                    //	ike2.LocalIdentifier = "";
                    ike2.RemoteIdentifier          = "hide.me";
                    ike2.UseExtendedAuthentication = true;
                    ike2.DisconnectOnSleep         = false;

                    // ipSec Protocol
                    NEVpnProtocolIpSec ipSec        = new NEVpnProtocolIpSec();
                    ipSec.AuthenticationMethod      = NEVpnIkeAuthenticationMethod.SharedSecret;
                    ipSec.UseExtendedAuthentication = true;
                    ipSec.DisconnectOnSleep         = false;
                    SecStatusCode res;

                    // Set the shared secret reference for ipSec:
                    // 1) Search for the secret in keychain and retrieve it as a persistent reference
                    // 2) Set the found secret to SharedSecretReference if the secret was found
                    var match = SecKeyChain.QueryAsData(querySecret, true, out res);
                    if (res == SecStatusCode.Success)
                    {
                        Console.WriteLine("Secret found, setting secret...");
                        ipSec.SharedSecretReference = match;
                    }
                    else
                    {
                        Console.WriteLine("Could not set secret:");
                        Console.WriteLine(res);
                    }

                    // Set the protocol to IKEv2 or ipSec
                    //		p = ike2;
                    p = ipSec;

                    // Set Accountname, Servername and description
                    p.Username      = "******";
                    p.ServerAddress = "free-nl.hide.me";
                    manager.LocalizedDescription = "hide.me VPN";

                    // Set the password reference for the protocol:
                    // 1) Search for the password in keychain and retrieve it as a persistent reference
                    // 2) Set the found password to PasswordReference if the secret was found
                    match = SecKeyChain.QueryAsData(queryPassword, true, out res);
                    if (res == SecStatusCode.Success)
                    {
                        Console.WriteLine("Password found, setting password...");
                        p.PasswordReference = match;
                    }
                    else
                    {
                        Console.WriteLine(res);
                    }
                    manager.OnDemandEnabled = false;

                    // Set the managers protocol and save it to the iOS custom VPN preferences
                    manager.ProtocolConfiguration = p;
                    manager.SaveToPreferences(error2 => {
                        if (error2 != null)
                        {
                            Console.WriteLine("Could not save VPN preferences");
                            Console.WriteLine(error2.DebugDescription);
                        }
                    });
                }
            });
        }
Example #40
0
 public AVAssetDownloadTask GetAssetDownloadTask(AVUrlAsset urlAsset, string title, NSData artworkData, AVAssetDownloadOptions options)
 {
     throw new NotImplementedException();
 }
Example #41
0
        public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
        {
            ParseInstallation installation = ParseInstallation.CurrentInstallation;

            installation.SetDeviceTokenFromData(deviceToken);

            installation.SaveAsync();
        }
Example #42
0
 public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
 => this.ShinyRegisteredForRemoteNotifications(deviceToken);
Example #43
0
 public virtual void WriteValue(global::MonoTouch.CoreBluetooth.CBUUID serviceUUID, global::MonoTouch.CoreBluetooth.CBUUID characteristicUUID, global::MonoTouch.CoreBluetooth.CBPeripheral p, NSData data)
 {
     if (serviceUUID == null)
     {
         throw new ArgumentNullException("serviceUUID");
     }
     if (characteristicUUID == null)
     {
         throw new ArgumentNullException("characteristicUUID");
     }
     if (p == null)
     {
         throw new ArgumentNullException("p");
     }
     if (data == null)
     {
         throw new ArgumentNullException("data");
     }
     if (IsDirectBinding)
     {
         MonoTouch.ObjCRuntime.Messaging.void_objc_msgSend_IntPtr_IntPtr_IntPtr_IntPtr(this.Handle, selWriteValueCharacteristicUUIDPData_Handle, serviceUUID.Handle, characteristicUUID.Handle, p.Handle, data.Handle);
     }
     else
     {
         MonoTouch.ObjCRuntime.Messaging.void_objc_msgSendSuper_IntPtr_IntPtr_IntPtr_IntPtr(this.SuperHandle, selWriteValueCharacteristicUUIDPData_Handle, serviceUUID.Handle, characteristicUUID.Handle, p.Handle, data.Handle);
     }
 }
Example #44
0
 public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
 {
     registeredDeviceToken = deviceToken.ToString();
     base.RegisteredForRemoteNotifications(application, deviceToken);
 }
Example #45
0
 public override NSUrlSessionUploadTask CreateUploadTask(NSUrlRequest request, NSData bodyData)
 {
     throw new NotImplementedException();
 }
Example #46
0
        //int? IGallery.ImagesSelection
        //{
        //    get
        //    {
        //        return Convert.ToInt32(Xamarin.Forms.Application.Current.Properties["ImagesSelection"]);
        //    }

        //    set
        //    {
        //        Xamarin.Forms.Application.Current.Properties["ImagesSelection"] = value;
        //    }
        //}

        public void OpenGallery(int imageselection)
        {
            try
            {
                var  picker    = ELCImagePickerViewController.Create(imageselection, "Select Images");
                int  Totalsize = 0;
                bool IsValid   = true;
                picker.Completion.ContinueWith(t =>
                {
                    picker.BeginInvokeOnMainThread(() =>
                    {
                        lstBytes   = new List <byte[]>();
                        _imagename = new List <string>();
                        picker.DismissViewController(true, null);
                        #region
                        if (t.IsCanceled || t.Exception != null)
                        {
                            //cancelled or error
                        }
                        else
                        {
                            //get the selected items
                            var items = t.Result as List <AssetResult>;
                            foreach (AssetResult aItem in items)
                            {
                                string Extension   = aItem.Name.Substring(aItem.Name.IndexOf('.') + 1, aItem.Name.Length - aItem.Name.IndexOf('.') - 1);
                                UIImage objUIImage = aItem.Image;
                                NSData imagedata   = new NSData();
                                if (Extension.ToLower() == "png")
                                {
                                    imagedata = objUIImage.AsPNG();
                                }
                                else
                                {
                                    imagedata = objUIImage.AsJPEG();
                                }
                                byte[] bytes = new byte[imagedata.Length];
                                Totalsize   += bytes.Length;
                                if (Totalsize > 10000000)
                                {
                                    IsValid = false;
                                    MessagingCenter.Send <App, string>((App)Xamarin.Forms.Application.Current, "imagevalidation", "Image Cannot be Greater than 10 MB");
                                    break;
                                }
                                System.Runtime.InteropServices.Marshal.Copy(imagedata.Bytes, bytes, 0, Convert.ToInt32(imagedata.Length));
                                lstBytes.Add(bytes);
                                _imagename.Add(aItem.Name);
                            }


                            if (IsValid)
                            {
                                if (_imagename.Count > 0)
                                {
                                    MessagingCenter.Send <App, List <byte[]> >((App)Xamarin.Forms.Application.Current, "ImagesSelected", lstBytes);
                                    MessagingCenter.Send <App, List <string> >((App)Xamarin.Forms.Application.Current, "ImagesSelectedName", _imagename);
                                }
                                else
                                {
                                    MessagingCenter.Send <App, string>((App)Xamarin.Forms.Application.Current, "exception", "");
                                }
                            }
                        }



                        #endregion
                    });
                });

                var topController = UIApplication.SharedApplication.KeyWindow.RootViewController;
                while (topController.PresentedViewController != null)
                {
                    topController = topController.PresentedViewController;
                }
                topController.PresentViewController(picker, true, null);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Example #47
0
 public override NSUrlSessionDownloadTask CreateDownloadTask(NSData resumeData)
 {
     throw new NotImplementedException();
 }
Example #48
0
        public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
        {
            DeviceToken = deviceToken.Description;
            DeviceToken = DeviceToken.Trim('<', '>').Replace(" ", "");

            MobileServiceClient client = new MobileServiceClient(ApplicationUrl, ApplicationKey);

            string userid = NSUserDefaults.StandardUserDefaults.StringForKey("CrmUserId");

            if (string.IsNullOrEmpty(userid))
            {
                return;
            }

            //Tags could be expanded to handle multiple different scenarios
            IEnumerable <string> tags = new List <string>()
            {
                userid, "All Users"
            };
            var push = client.GetPush();

            push.RegisterNativeAsync(DeviceToken, tags);
        }
Example #49
0
        public override void ViewDidLoad()
        {
            Console.WriteLine("HomeListNavigationController ViewDidLoad");
            _homeListViewController = new HomeListViewController();

            NavigationBar.TintColor = UIColor.DarkGray;

            // go to new comparison view if add button is touched
            _homeListViewController.OnAddComparison += (sender, args) =>
            {
                _comparisonViewController = new ComparisonViewController();

                // when a new comparison is added
                // select the created comparison in the shopping list controller
                _comparisonViewController.OnFinished += (sender_, args_) =>
                {
                    if (_comparisonViewController.Comparison == null)
                    {
                        throw new Exception("New comparison id was not set.");
                    }

                    _homeListViewController.EnableTrashButton();
                    _homeListViewController.AddComparison(_comparisonViewController.Comparison);
                    DismissModalViewControllerAnimated(true);
                    _comparableViewController = null;
                };

                _comparisonViewController.OnCanceled += (sender_, args_) =>
                {
                    DismissModalViewControllerAnimated(true);
                    _comparisonViewController = null;
                };

                PresentModalViewController(_comparisonViewController, true);
            };

            // go to the created comparison's lineup view when a comparison is selected
            _homeListViewController.OnComparisonSelected += (sender, args) =>
            {
                _comparisonLineupViewController = new ComparisonLineupViewController(_homeListViewController.SelectedComparison);

                // new comparable
                _comparisonLineupViewController.OnAddComparable += (sender_, args_) =>
                {
                    _comparableViewController             = new ComparableViewController(_comparisonLineupViewController.ComparisonId);
                    _comparableViewController.OnFinished += (sender__, args__) =>
                    {
                        _comparisonLineupViewController.EnableTrashButton();
                        _comparisonLineupViewController.AddComparable(_comparableViewController.Comparable);
                        DismissModalViewControllerAnimated(true);
                        _comparableViewController = null;
                    };
                    _comparableViewController.OnCanceled += (sender__, args__) =>
                    {
                        DismissModalViewControllerAnimated(true);
                        _comparableViewController = null;
                    };
                    var navController = new UINavigationController(_comparableViewController);
                    PresentModalViewController(navController, true);
                };

                // edit comparable
                _comparisonLineupViewController.OnComparableSelected += (sender_, args_) =>
                {
                    _comparableViewController             = new ComparableViewController(_comparisonLineupViewController.GetSelectedComparable());
                    _comparableViewController.OnFinished += (sender__, args__) =>
                    {
                        // this fixes the bug where changing the "winning"
                        // comparable name was not reflected on the home list view
                        _homeListViewController.ReloadRowForComparison(_comparisonLineupViewController.ComparisonId);

                        _comparisonLineupViewController.RepositionRowForComparable(_comparisonLineupViewController.GetSelectedComparable().Id);
                        PopViewControllerAnimated(true);
                        _comparableViewController = null;
                    };
                    _comparableViewController.OnCanceled += (sender__, args__) =>
                    {
                        PopViewControllerAnimated(true);
                        _comparableViewController = null;
                    };
                    PushViewController(_comparableViewController, true);
                };

                // edit comparison
                _comparisonLineupViewController.OnModify += (sender_, args_) =>
                {
                    _comparisonViewController             = new ComparisonViewController(_homeListViewController.SelectedComparison);
                    _comparisonViewController.OnCanceled += (sender__, args__) =>
                    {
                        DismissModalViewControllerAnimated(true);
                    };

                    _comparisonViewController.OnFinished += (sender__, args__) =>
                    {
                        _comparisonLineupViewController.ReloadOnAppeared();
                        _homeListViewController.ReloadRowForComparison(_comparisonLineupViewController.ComparisonId);
                        _homeListViewController.RepositionRowForComparison(_comparisonLineupViewController.ComparisonId);
                        DismissModalViewControllerAnimated(true);
                    };
                    PresentModalViewController(_comparisonViewController, true);
                };

                _comparisonLineupViewController.OnNewCheaper += (sender__, args__) =>
                {
                    _homeListViewController.ReloadRowForComparison(_comparisonLineupViewController.ComparisonId);
                };

                PushViewController(_comparisonLineupViewController, true);
            };

            _homeListViewController.OnInfoButton += (sender, args) =>
            {
                _aboutViewController         = new AboutViewController();
                _aboutViewController.OnDone += (sender_, args_) =>
                {
                    DismissModalViewControllerAnimated(true);
                    _aboutViewController       = null;
                    _aboutNavigationController = null;
                    _emailController           = null;
                };
                _aboutViewController.OnFeedback += (sender_, args_) =>
                {
                    _emailController = new MFMailComposeViewController();
                    _emailController.SetToRecipients(new string[] { "*****@*****.**" });
                    _emailController.SetSubject("Feedback and bugs");
                    _emailController.Finished += (sender__, args__) =>
                    {
                        if (args__.Result == MFMailComposeResult.Sent)
                        {
                            new UIAlertView("Thank you", "We appreciate your feedback and you'll hear back from us soon!", null, "Ok").Show();
                        }
                        _aboutViewController.DismissModalViewControllerAnimated(true);
                        _emailController = null;
                    };

                    _aboutViewController.PresentModalViewController(_emailController, true);
                };
                _aboutViewController.OnBackupData += (sender_, args_) =>
                {
                    var attachmentFileName = string.Format("CheapsterBackup_{0}.cdbk", DateTime.Now.ToString("yyyyMMdd"));

                    if (!Directory.Exists(Configuration.TEMP_FOLDER))
                    {
                        Directory.CreateDirectory(Configuration.TEMP_FOLDER);
                    }

                    // compress the database
                    var zipFile = new LibZipArchive.ZipArchive();
                    zipFile.CreateZipFile2(Configuration.USER_DB_TEMP_ZIP_PATH);
                    zipFile.AddFile(Configuration.USER_DB_INSTALLED_PATH, Configuration.USER_DB_FILENAME);
                    zipFile.CloseZipFile2();

                    var fileData = NSData.FromFile(Configuration.USER_DB_TEMP_ZIP_PATH);
                    _emailController = new MFMailComposeViewController();
                    _emailController.SetSubject(string.Format("Cheapster Data Backup {0}", DateTime.Now.ToShortDateString()));
                    _emailController.SetMessageBody("Here is your Cheapster data. \n\n To restore from this backup, open this email in the Mail app, touch the file and hold down until a menu appears with an option for \"Open in Cheapster\".", false);
                    _emailController.AddAttachmentData(fileData, "Cheapster/x-cdbk", attachmentFileName);
                    _emailController.Finished += (sender__, args__) =>
                    {
                        if (args__.Result == MFMailComposeResult.Sent)
                        {
                            new UIAlertView("Email Sent", "", null, "Ok").Show();
                        }

                        _aboutViewController.DismissModalViewControllerAnimated(true);
                        _emailController = null;
                    };

                    _aboutViewController.PresentModalViewController(_emailController, true);
                };
                _aboutViewController.OnRateThisApp += (sender__, args__) =>
                {
                    var url = string.Format(_urlFormat, "375611783");
                    //UIApplication.SharedApplication.OpenUrl(NSUrl.FromString(url));
                    UIApplication.SharedApplication.OpenUrl(NSUrl.FromString("http://itunes.apple.com/us/app/cheapster/id426078800?mt=8&ls=1"));
                };
                _aboutViewController.OnTwitter += (sender__, args__) =>
                {
                    UIApplication.SharedApplication.OpenUrl(NSUrl.FromString("http://twitter.com/cheapsterapp"));
                };
                _aboutViewController.ModalTransitionStyle = UIModalTransitionStyle.FlipHorizontal;

                _aboutNavigationController = new UINavigationController();
                _aboutNavigationController.PushViewController(_aboutViewController, false);

                PresentModalViewController(_aboutNavigationController, true);
            };

            PushViewController(_homeListViewController, true);
            base.ViewDidLoad();
        }
Example #50
0
        void RequestShare(Dictionary <string, object> paramsDictionary)
        {
            if (paramsDictionary.TryGetValue("content", out object shareContent) && shareContent is FacebookShareContent)
            {
                ISharingContent content = null;
                if (shareContent is FacebookShareLinkContent)
                {
                    FacebookShareLinkContent linkContent  = shareContent as FacebookShareLinkContent;
                    ShareLinkContent         sLinkContent = new ShareLinkContent();


                    if (linkContent.Quote != null)
                    {
                        sLinkContent.Quote = linkContent.Quote;
                    }

                    if (linkContent.ContentLink != null)
                    {
                        sLinkContent.SetContentUrl(linkContent.ContentLink);
                    }

                    if (!string.IsNullOrEmpty(linkContent.Hashtag))
                    {
                        var shareHashTag = new Hashtag();
                        shareHashTag.StringRepresentation = linkContent.Hashtag;
                        sLinkContent.Hashtag = shareHashTag;
                    }

                    if (linkContent.PeopleIds != null && linkContent.PeopleIds.Length > 0)
                    {
                        sLinkContent.SetPeopleIds(linkContent.PeopleIds);
                    }

                    if (!string.IsNullOrEmpty(linkContent.PlaceId))
                    {
                        sLinkContent.SetPlaceId(linkContent.PlaceId);
                    }

                    if (!string.IsNullOrEmpty(linkContent.Ref))
                    {
                        sLinkContent.SetRef(linkContent.Ref);
                    }

                    content = sLinkContent;
                }
                else if (shareContent is FacebookSharePhotoContent)
                {
                    FacebookSharePhotoContent photoContent = shareContent as FacebookSharePhotoContent;

                    SharePhotoContent sharePhotoContent = new SharePhotoContent();

                    if (photoContent.Photos != null && photoContent.Photos.Length > 0)
                    {
                        List <SharePhoto> photos = new List <SharePhoto>();
                        foreach (var p in photoContent.Photos)
                        {
                            if (p.ImageUrl != null && !string.IsNullOrEmpty(p.ImageUrl.AbsoluteUri))
                            {
                                SharePhoto photoFromUrl = SharePhoto.From(p.ImageUrl, true);

                                if (!string.IsNullOrEmpty(p.Caption))
                                {
                                    photoFromUrl.Caption = p.Caption;
                                }

                                photos.Add(photoFromUrl);
                            }

                            if (p.Image != null)
                            {
                                UIImage image = null;

                                var imageBytes = p.Image as byte[];

                                if (imageBytes != null)
                                {
                                    using (var data = NSData.FromArray(imageBytes))
                                        image = UIImage.LoadFromData(data);

                                    SharePhoto sPhoto = Facebook.ShareKit.SharePhoto.From(image, true);

                                    if (!string.IsNullOrEmpty(p.Caption))
                                    {
                                        sPhoto.Caption = p.Caption;
                                    }


                                    photos.Add(sPhoto);
                                }
                            }
                        }

                        if (photos.Count > 0)
                        {
                            sharePhotoContent.Photos = photos.ToArray();
                        }
                    }

                    if (photoContent.ContentLink != null)
                    {
                        sharePhotoContent.SetContentUrl(photoContent.ContentLink);
                    }

                    if (!string.IsNullOrEmpty(photoContent.Hashtag))
                    {
                        var shareHashTag = new Hashtag();
                        shareHashTag.StringRepresentation = photoContent.Hashtag;
                        sharePhotoContent.Hashtag         = (shareHashTag);
                    }

                    if (photoContent.PeopleIds != null && photoContent.PeopleIds.Length > 0)
                    {
                        sharePhotoContent.SetPeopleIds(photoContent.PeopleIds);
                    }

                    if (!string.IsNullOrEmpty(photoContent.PlaceId))
                    {
                        sharePhotoContent.SetPlaceId(photoContent.PlaceId);
                    }

                    if (!string.IsNullOrEmpty(photoContent.Ref))
                    {
                        sharePhotoContent.SetRef(photoContent.Ref);
                    }

                    content = sharePhotoContent;
                }
                else if (shareContent is FacebookShareVideoContent)
                {
                    FacebookShareVideoContent videoContent      = shareContent as FacebookShareVideoContent;
                    ShareVideoContent         shareVideoContent = new ShareVideoContent();


                    if (videoContent.PreviewPhoto != null)
                    {
                        if (videoContent.PreviewPhoto.ImageUrl != null && !string.IsNullOrEmpty(videoContent.PreviewPhoto.ImageUrl.AbsoluteUri))
                        {
                            SharePhoto photoFromUrl = Facebook.ShareKit.SharePhoto.From(videoContent.PreviewPhoto.ImageUrl, true);

                            if (!string.IsNullOrEmpty(videoContent.PreviewPhoto.Caption))
                            {
                                photoFromUrl.Caption = videoContent.PreviewPhoto.Caption;
                            }

                            shareVideoContent.PreviewPhoto = photoFromUrl;
                        }

                        if (videoContent.PreviewPhoto.Image != null)
                        {
                            UIImage image = null;

                            var imageBytes = videoContent.PreviewPhoto.Image as byte[];

                            if (imageBytes != null)
                            {
                                using (var data = NSData.FromArray(imageBytes))
                                    image = UIImage.LoadFromData(data);

                                SharePhoto photo = Facebook.ShareKit.SharePhoto.From(image, true);

                                if (!string.IsNullOrEmpty(videoContent.PreviewPhoto.Caption))
                                {
                                    photo.Caption = videoContent.PreviewPhoto.Caption;
                                }


                                shareVideoContent.PreviewPhoto = photo;
                            }
                        }
                    }

                    if (videoContent.Video != null)
                    {
                        if (videoContent.Video.LocalUrl != null)
                        {
                            shareVideoContent.Video = ShareVideo.From(videoContent.Video.LocalUrl);
                        }
                    }

                    if (videoContent.ContentLink != null)
                    {
                        shareVideoContent.SetContentUrl(videoContent.ContentLink);
                    }

                    if (!string.IsNullOrEmpty(videoContent.Hashtag))
                    {
                        var shareHashTag = new Hashtag();
                        shareHashTag.StringRepresentation = videoContent.Hashtag;
                        shareVideoContent.Hashtag         = (shareHashTag);
                    }

                    if (videoContent.PeopleIds != null && videoContent.PeopleIds.Length > 0)
                    {
                        shareVideoContent.SetPeopleIds(videoContent.PeopleIds);
                    }

                    if (!string.IsNullOrEmpty(videoContent.PlaceId))
                    {
                        shareVideoContent.SetPlaceId(videoContent.PlaceId);
                    }

                    if (!string.IsNullOrEmpty(videoContent.Ref))
                    {
                        shareVideoContent.SetRef(videoContent.Ref);
                    }

                    content = shareVideoContent;
                }

                if (content != null)
                {
                    //ShareAPI.Share(content, this);

                    var window = UIApplication.SharedApplication.KeyWindow;
                    var vc     = window.RootViewController;
                    while (vc.PresentedViewController != null)
                    {
                        vc = vc.PresentedViewController;
                    }

                    ShareDialog.Show(vc, content, this);
                }
            }
        }
        private void HandlePersistableContentKeyRequest(AVPersistableContentKeyRequest keyRequest)
        {
            /*
             * The key ID is the URI from the EXT-X-KEY tag in the playlist (e.g. "skd://key65") and the
             * asset ID in this case is "key65".
             */

            var contentKeyIdentifierString = keyRequest.Identifier as NSString;

            if (contentKeyIdentifierString == null)
            {
                Debug.WriteLine("Failed to retrieve the assetID from the keyRequest!");
                return;
            }

            var contentKeyIdentifierUrl = new NSUrl(contentKeyIdentifierString);
            var assetIdString           = contentKeyIdentifierUrl.Host;
            var assetIdData             = NSData.FromString(assetIdString, NSStringEncoding.UTF8);

            Action <NSData, NSError> completionHandler = async(data, error) =>
            {
                if (error != null)
                {
                    keyRequest.Process(error);
                    pendingPersistableContentKeyIdentifiers.Remove(assetIdString);
                    return;
                }

                if (data == null)
                {
                    return;
                }

                try
                {
                    var ckcData = await RequestContentKeyFromKeySecurityModule(data, assetIdString);

                    NSData persistentKey = keyRequest.GetPersistableContentKey(ckcData, null, out error);

                    WritePersistableContentKey(persistentKey, new NSString(assetIdString));

                    /*
                     * AVContentKeyResponse is used to represent the data returned from the key server when requesting a key for
                     * decrypting content.
                     */
                    var keyResponse = AVContentKeyResponse.Create(persistentKey);

                    /*
                     * Provide the content key response to make protected content available for processing.
                     */
                    keyRequest.Process(keyResponse);

                    string assetName    = string.Empty;
                    bool   assetRemoved = false;

                    if (contentKeyToStreamNameMap.TryGetValue(assetIdString, out assetName))
                    {
                        assetRemoved = contentKeyToStreamNameMap.Remove(assetIdString);
                    }

                    if (!string.IsNullOrWhiteSpace(assetName) && assetRemoved && !contentKeyToStreamNameMap.ContainsKey(assetIdString))
                    {
                        var userInfo = new Dictionary <string, object>();
                        userInfo["name"] = assetName;

                        var userInfoDictionary = NSDictionary.FromObjectsAndKeys(userInfo.Values.ToArray(), userInfo.Keys.ToArray());
                        NSNotificationCenter.DefaultCenter.PostNotificationName(ContentKeyDelegate.DidSaveAllPersistableContentKey, null, userInfoDictionary);
                    }

                    pendingPersistableContentKeyIdentifiers.Remove(assetIdString);
                }
                catch (Exception ex)
                {
                    pendingPersistableContentKeyIdentifiers.Remove(assetIdString);
                    Debug.WriteLine(ex.Message);
                }
            };

            try
            {
                var applicationCertificate = RequestApplicationCertificate();

                var keys    = new[] { new NSString(AVContentKeyRequest.ProtocolVersions) };
                var numbers = new NSMutableArray <NSNumber>();
                numbers.Add(new NSNumber(1));
                var objects = new NSObject[] { numbers };
                var options = new NSDictionary <NSString, NSObject>(keys, objects);

                if (PersistableContentKeyExistsOnDisk(assetIdString))
                {
                    var urlToPersistableKey = CreateUrlForPersistableContentKey(assetIdString);
                    var contentKey          = NSFileManager.DefaultManager.Contents(urlToPersistableKey.Path);

                    if (contentKey == null)
                    {
                        pendingPersistableContentKeyIdentifiers.Remove(assetIdString);

                        /*
                         * Key requests should never be left dangling.
                         * Attempt to create a new persistable key.
                         */
                        keyRequest.MakeStreamingContentKeyRequestData(applicationCertificate, assetIdData, options, completionHandler);

                        return;
                    }

                    /*
                     * Create an AVContentKeyResponse from the persistent key data to use for requesting a key for
                     * decrypting content.
                     */

                    var keyResponse = AVContentKeyResponse.Create(contentKey);
                    keyRequest.Process(keyResponse);

                    return;
                }

                keyRequest.MakeStreamingContentKeyRequestData(applicationCertificate, assetIdData, options, completionHandler);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Failure responding to an AVPersistableContentKeyRequest when attemping to determine if key is already available for use on disk. {ex.Message}");
            }
        }
Example #52
0
        void RequestData(Dictionary <string, object> pDictionary)
        {
            string path    = $"{pDictionary["path"]}";
            string version = $"{pDictionary["version"]}";
            Dictionary <string, string> paramDict = pDictionary["parameters"] as Dictionary <string, string>;
            FacebookHttpMethod?         method    = pDictionary["method"] as FacebookHttpMethod?;
            var currentTcs = _requestTcs;
            var onEvent    = OnRequestData;
            var httpMethod = "GET";

            if (method != null)
            {
                switch (method)
                {
                case FacebookHttpMethod.Get:
                    httpMethod = "GET";
                    break;

                case FacebookHttpMethod.Post:
                    httpMethod = "POST";
                    onEvent    = OnPostData;
                    currentTcs = _postTcs;
                    break;

                case FacebookHttpMethod.Delete:
                    httpMethod = "DELETE";
                    onEvent    = OnDeleteData;
                    currentTcs = _deleteTcs;
                    break;
                }
            }

            if (string.IsNullOrEmpty(path))
            {
                var fbResponse = new FBEventArgs <string>(null, FacebookActionStatus.Error, "Graph query path not specified");
                onEvent?.Invoke(CrossFacebookClient.Current, fbResponse);
                currentTcs?.TrySetResult(new FacebookResponse <string>(fbResponse));
                return;
            }



            NSMutableDictionary parameters = null;

            if (paramDict != null)
            {
                parameters = new NSMutableDictionary();
                foreach (var p in paramDict)
                {
                    if (!string.IsNullOrEmpty(p.Key) && !string.IsNullOrEmpty(p.Value))
                    {
                        parameters.Add(new NSString($"{p.Key}"), new NSString($"{p.Value}"));
                    }
                }
            }

            var graphRequest      = string.IsNullOrEmpty(version)?new GraphRequest(path, parameters, httpMethod): new GraphRequest(path, parameters, AccessToken.CurrentAccessToken.TokenString, version, httpMethod);
            var requestConnection = new GraphRequestConnection();

            requestConnection.AddRequest(graphRequest, (connection, result, error) =>
            {
                if (error == null)
                {
                    NSData responseData = NSJsonSerialization.Serialize(result, NSJsonWritingOptions.PrettyPrinted, out NSError jsonError);
                    if (jsonError == null)
                    {
                        NSString responseString = NSString.FromData(responseData, NSStringEncoding.UTF8);
                        var fbResponse          = new FBEventArgs <string>(responseString, FacebookActionStatus.Completed);
                        onEvent?.Invoke(CrossFacebookClient.Current, fbResponse);
                        currentTcs?.TrySetResult(new FacebookResponse <string>(fbResponse));
                    }
                    else
                    {
                        var fbResponse = new FBEventArgs <string>(null, FacebookActionStatus.Error, $" Facebook response parse failed - {jsonError.Code} - {jsonError.Description}");
                        onEvent?.Invoke(CrossFacebookClient.Current, fbResponse);
                        currentTcs?.TrySetResult(new FacebookResponse <string>(fbResponse));
                    }
                }
                else
                {
                    var fbResponse = new FBEventArgs <string>(null, FacebookActionStatus.Error, $" Facebook operation failed - {error.Code} - {error.Description}");
                    onEvent?.Invoke(CrossFacebookClient.Current, fbResponse);
                    currentTcs?.TrySetResult(new FacebookResponse <string>(fbResponse));
                }
            });
            requestConnection.Start();
        }
Example #53
0
 // Override Methods:
 public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
 {
     Messaging.SharedInstance.ApnsToken = deviceToken;
 }
 /// <summary>
 ///     Initializes a new instance of the <see cref="NsDataStream" /> class.
 /// </summary>
 /// <param name="data">The data.</param>
 public NsDataStream(NSData data)
     : base((byte *)data.Bytes, (long)data.Length)
 {
     _data = data;
 }
Example #55
0
        public async Task <NSError> WriteValue(CBPeripheral peripheral, CBCharacteristic characteristic, NSData value)
        {
            var taskCompletion = new TaskCompletionSource <NSError>();
            var task           = taskCompletion.Task;
            EventHandler <CBCharacteristicEventArgs> handler = (s, e) =>
            {
                if (e.Characteristic.UUID?.Uuid == characteristic.UUID?.Uuid)
                {
                    taskCompletion.SetResult(e.Error);
                }
            };

            try
            {
                peripheral.WroteCharacteristicValue += handler;
                peripheral.WriteValue(value, characteristic, CBCharacteristicWriteType.WithResponse);
                await this.WaitForTaskWithTimeout(task, ConnectionTimeout);

                return(task.Result);
            }
            finally
            {
                peripheral.WroteCharacteristicValue -= handler;
            }
        }
Example #56
0
 public virtual AVAssetDownloadTask GetAssetDownloadTask(AVUrlAsset urlAsset, string title, NSData artworkData, NSDictionary options)
 {
     throw new NotImplementedException();
 }
Example #57
0
 public static CIImage FromData(NSData bitmapData, nint bytesPerRow, CGSize size, CIFormat pixelFormat, CGColorSpace colorSpace)
 {
     return(FromData(bitmapData, bytesPerRow, size, CIImage.CIFormatToInt(pixelFormat), colorSpace));
 }
Example #58
0
 public override NSUrlSessionUploadTask CreateUploadTask(NSUrlRequest request, NSData bodyData, NSUrlSessionResponse completionHandler)
 {
     throw new NotImplementedException();
 }
Example #59
0
 public static SCNGeometrySource FromData(NSData data, SCNGeometrySourceSemantics semantic, nint vectorCount, bool floatComponents, nint componentsPerVector, nint bytesPerComponent, nint offset, nint stride)
 {
     return(FromData(data, SemanticToToken(semantic), vectorCount, floatComponents, componentsPerVector, bytesPerComponent, offset, stride));
 }
 //[Verify (PlatformInvoke)]
 static extern GLMapResource GLMapResourceWithData(NSData data);