private void HandleFacebookError(NSError error)
		{
			if (FBErrorUtility.ShouldNotifyUser(error))
			{
				string errorText = FBErrorUtility.UserMessage(error);
				UIAlertView alertView = new UIAlertView("APP/ALERT/TITLE/ERROR".Localize(), errorText, null, "APP/ALERT/BUTTON/OK".Localize(), null);
				alertView.Show();
			}
			else
			{
				if (FBErrorUtility.ErrorCategory(error) == FBErrorCategory.UserCancelled)
				{
					Console.WriteLine("Facebook login cancelled by user.");
				}
				else if (FBErrorUtility.ErrorCategory(error) == FBErrorCategory.AuthenticationReopenSession)
				{
					UIAlertView alertView = new UIAlertView("APP/ALERT/TITLE/ERROR".Localize(), "APP/FACEBOOK/ERRORS/RELOGIN".Localize(), null, "APP/ALERT/BUTTON/OK".Localize(), null);
					alertView.Show();
				}
				else
				{
					UIAlertView alertView = new UIAlertView("APP/ALERT/TITLE/ERROR".Localize(), "APP/FACEBOOK/ERRORS/GENERAL".Localize(), null, "APP/ALERT/BUTTON/OK".Localize(), null);
					alertView.Show();
				}
			}
			Interfaces.Instance.FacebookInterface.Close(true);
		}
        public NSAttributedString GetAttributedText()
        {
            string path = null;
            NSError error = new NSError ();

            if (TextStoragePath != null)
                path = NSBundle.MainBundle.PathForResource ("TextFiles/" + TextStoragePath[0], "");
            else
                path = NSBundle.MainBundle.PathForResource ("TextFiles/" + Title, "rtf");

            if (path == null)
                return new NSAttributedString ("");

            if (StrRichFormatting) {
                //  Load the file from disk
                var attributedString = new NSAttributedString (new NSUrl (path, false), null, ref error);

                // Make a copy we can alter
                var attributedTextHolder = new NSMutableAttributedString (attributedString);

                attributedTextHolder.AddAttributes (new UIStringAttributes () { Font = UIFont.PreferredBody },
                    new NSRange (0, attributedTextHolder.Length));
                AttributedText = (NSAttributedString)attributedTextHolder.Copy ();
            } else {
                string newFlatText = new NSAttributedString (new NSUrl (path, false), null, ref error).Value;
                AttributedText = new NSAttributedString (newFlatText, font: UIFont.PreferredBody);
            }

            return AttributedText;
        }
 public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
 {
     if (CrossPushNotification.Current is IPushNotificationHandler)
     {
         ((IPushNotificationHandler)CrossPushNotification.Current).OnErrorReceived(error);
     }
 }
 public IPhoneUIApplicationDelegate()
     : base()
 {
     #if DEBUG
     log ("IPhoneUIApplicationDelegate constructor default");
     #endif
     IPhoneServiceLocator.CurrentDelegate = this;
     #if DEBUG
     log ("IPhoneUIApplicationDelegate creating event store instance");
     #endif
     eventStore = new EKEventStore ( );
     #if DEBUG
     log ("IPhoneUIApplicationDelegate creating address book instance");
     #endif
     if (UIDevice.CurrentDevice.CheckSystemVersion (6, 0)) {
         NSError nsError = new NSError();
         addressBook =ABAddressBook.Create(out nsError);
         #if DEBUG
         log ("IPhoneUIApplicationDelegate creating address book result: " +((nsError!=null)?nsError.Description:"no error"));
         #endif
     } else {
         addressBook = new ABAddressBook();
     }
     #if DEBUG
     log ("IPhoneUIApplicationDelegate constructor successfully ended");
     #endif
 }
		/// <summary>
		/// called as the completion handler to requesting access to the calendar
		/// </summary>
		protected void PopulateCalendarList (bool grantedAccess, NSError e)
		{
			// if it err'd show it to the user
			if ( e != null ) {
				Console.WriteLine ( "Err: " + e.ToString () );
				new UIAlertView ( "Error", e.ToString(), null, "ok", null ).Show();
				return;
			}

			// if the user granted access to the calendar data
			if (grantedAccess) {
				// get calendars of the particular type (either events or reminders)
				calendars = App.Current.EventStore.GetCalendars ( entityType );

				// build out an MT.D list of all the calendars, we show the calendar title
				// as well as the source (where the calendar is pulled from, like iCloud, local
				// exchange, etc.)
				calendarListRoot.Add (
					new Section ( ) { 
						from elements in calendars
						select ( Element ) new StringElement ( elements.Title, elements.Source.Title )
					}
				);

				this.InvokeOnMainThread ( () => { this.Root = calendarListRoot; } ); 
			}
			// if the user didn't grant access, show an alert
			else {
				Console.WriteLine ( "Access denied by user. " );
				InvokeOnMainThread ( () => { 
					new UIAlertView ( "No Access", "Access to calendar not granted", null, "ok", null).Show ();
				});
			}
		}
		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}");
		}
Beispiel #7
0
		public static List<StockDataPoint> LoadStockPoints(int maxItems)
		{
			List<StockDataPoint> stockPoints = new List<StockDataPoint> ();

			string filePath = NSBundle.MainBundle.PathForResource ("AppleStockPrices", "json");
			NSData json = NSData.FromFile (filePath);
			NSError error = new NSError ();
			NSArray data = (NSArray)NSJsonSerialization.Deserialize (json, NSJsonReadingOptions.AllowFragments, out error);
			NSDateFormatter formatter = new NSDateFormatter ();
			formatter.DateFormat = "dd-MM-yyyy";

			for (int i = 0; i < (int)data.Count; i++) {
				if (i == maxItems) {
					break;
				}
				NSDictionary jsonPoint = data.GetItem<NSDictionary> ((nuint)i);
				StockDataPoint dataPoint = new StockDataPoint ();
				dataPoint.DataXValue = formatter.Parse ((NSString)jsonPoint ["date"]);
				dataPoint.Open = (NSNumber)jsonPoint ["open"];
				dataPoint.Low = (NSNumber)jsonPoint ["low"];
				dataPoint.Close = (NSNumber)jsonPoint ["close"];
				dataPoint.Volume = (NSNumber)jsonPoint ["volume"];
				dataPoint.High = (NSNumber)jsonPoint ["high"];
				stockPoints.Add (dataPoint);
			}

			return stockPoints;
		}
        private void FoundResults(ParseObject[] array, NSError error)
        {
            var easySection = new Section("Easy");
            var mediumSection = new Section("Medium");
            var hardSection = new Section("Hard");

            var objects = array.Select(x=> x.ToObject<GameScore>()).OrderByDescending(x=> x.Score).ToList();

            foreach(var score in objects)
            {
                var element = new StringElement(score.Player,score.Score.ToString("#,###"));
                switch(score.Dificulty)
                {
                case GameDificulty.Easy:
                    easySection.Add(element);
                    break;
                case GameDificulty.Medium:
                    mediumSection.Add(element);
                    break;
                case GameDificulty.Hard:
                    hardSection.Add (element);
                    break;
                }
            }
            Root = new RootElement("High Scores")
            {
                easySection,
                mediumSection,
                hardSection,
            };
        }
 void CompletedHandler(UIImage image, NSError error, SDImageCacheType cacheType)
 {
     if (activityIndicator != null) {
         activityIndicator.RemoveFromSuperview ();
         activityIndicator = null;
     }
 }
        public DetailViewController(RSSFeedItem item)
            : base(UITableViewStyle.Grouped, null, true)
        {
            var attributes = new NSAttributedStringDocumentAttributes();
              attributes.DocumentType = NSDocumentType.HTML;
              attributes.StringEncoding = NSStringEncoding.UTF8;
              var error = new NSError();
              var htmlString = new NSAttributedString(item.Description, attributes, ref error);

              Root = new RootElement(item.Title) {
                new Section{
                new StringElement(item.Author),
                new StringElement(item.PublishDate),
                        new StyledMultilineElement(htmlString),
                new HtmlElement("Full Article", item.Link)
              }
            };

            NavigationItem.RightBarButtonItem = new UIBarButtonItem(UIBarButtonSystemItem.Action, async delegate
                {
                    var message = item.Title + " " + item.Link + " #PlanetXamarin";
                    var social = new UIActivityViewController(new NSObject[] { new NSString(message)},
                        new UIActivity[] { new UIActivity() });
                    PresentViewController(social, true, null);
                });
        }
Beispiel #11
0
        //        /// <summary>
        //        /// Indicates whether this transaction has any downloads.
        //        /// </summary>
        //        [Obsolete("Use the hasDownloads property.")]
        //        public readonly bool HasDownloads = false;
        /// <summary>
        /// Initializes a new instance of the <see cref="U3DXT.iOS.IAP.TransactionEventArgs"/> class.
        /// </summary>
        /// <param name="transaction">Transaction.</param>
        /// <param name="error">Error.</param>
        public TransactionEventArgs(SKPaymentTransaction transaction, NSError error = null)
        {
            this.transaction = transaction;

            try {
                hasDownloads = (transaction.downloads != null);
            } catch (Exception) {
            }

            if (error != null)
                this.error = error;
            else
                this.error = transaction.error;

            if ((transaction.transactionState == SKPaymentTransactionState.Restored)
                && (transaction.originalTransaction != null)) {
                transaction = transaction.originalTransaction;
            }

            productID = transaction.payment.productIdentifier;
            quantity = transaction.payment.quantity;

            //			this.HasDownloads = this.hasDownloads;
            //			this.Error = this.error;
            //			this.ProductID = this.productID;
            //			this.Quantity = this.quantity;
        }
Beispiel #12
0
		private void HandleImageLoaded(UIImage image, NSError error, SDImageCacheType cacheType, NSUrl imageUrl)
		{
			if (error != null) {
				ErrorLabel.Hidden = false;
				LoadingIndicator.StopAnimating ();
			}
		}
 public override void DiscoveredService(CBPeripheral peripheral, NSError error)
 {
     System.Console.WriteLine ("Discovered a service");
     foreach (var service in peripheral.Services) {
         Console.WriteLine (service.ToString ());
         peripheral.DiscoverCharacteristics (service);
     }
 }
		public static void DidFailAd (this IGADCustomEventInterstitialDelegate This, GADCustomEventInterstitial customEvent, NSError error)
		{
			if (customEvent == null)
				throw new ArgumentNullException ("customEvent");
			if (error == null)
				throw new ArgumentNullException ("error");
			MonoTouch.ObjCRuntime.Messaging.void_objc_msgSend_IntPtr_IntPtr (This.Handle, Selector.GetHandle ("customEventInterstitial:didFailAd:"), customEvent.Handle, error.Handle);
		}
Beispiel #15
0
		void PrintingComplete (UIPrintInteractionController printInteractionController, bool completed, NSError error)
		{
			if (completed && error != null) {
				string message = String.Format ("Due to error in domain `{0}` with code: {1}", error.Domain, error.Code);
				Console.WriteLine ("FAILED! {0}", message);
				new UIAlertView ("Failed!", message, null, "OK", null).Show ();
			}
		}
		public virtual void NetworkFailed(NSError error){
			Loading = false;
			InvokeOnMainThread(()=>{
				using (var popup = new UIAlertView("Error", error.LocalizedDescription, null, "OK")){
					popup.Show();
				}
			});
		}
 public override void FailedToRegisterForRemoteNotifications(
   UIApplication application,
   NSError error)
 {
     DonkyiOS.FailedToRegisterForRemoteNotifications(
     application,
     error);
 }
        protected override void OnLoadError(NSError e)
        {
            base.OnLoadError(e);

            //Frame interrupted error
            if (e.Code == 102 || e.Code == -999) return;
            AlertDialogService.ShowAlert("Error", "Unable to communicate with GitHub. " + e.LocalizedDescription);
        }
 public override void DiscoveredCharacteristic(CBPeripheral peripheral, CBService service, NSError error)
 {
     System.Console.WriteLine ("Discovered characteristics of " + peripheral);
     foreach (var c in service.Characteristics) {
         Console.WriteLine (c.ToString ());
         peripheral.ReadValue (c);
     }
 }
		void CompletedHandler (UIImage image, NSError error, SDImageCacheType cacheType, NSUrl url)
		{
			if (activityIndicator != null) {
				InvokeOnMainThread (() => {
					activityIndicator.RemoveFromSuperview ();
					activityIndicator = null;
				});
			}
		}
Beispiel #21
0
 void OnCustomFoundMatch(GKMatch match, NSError error)
 {
     if (error != null) {
         Log("Error with matchmaker: " + error.LocalizedDescription());
     } else if (match != null) {
         // set the high-level match, and it will raise MatchMakerFoundMatch event
         RealTimeMatchesController.SetCurrentMatch(match);
     }
 }
Beispiel #22
0
 //        /// <summary>
 //        /// Whether the operation was completed.
 //        /// </summary>
 //        [Obsolete("Use the completed property.")]
 //        public readonly bool Completed;
 /// <summary>
 /// Initializes a new instance of the <see cref="U3DXT.iOS.Social.MailCompletedEventArgs"/> class.
 /// </summary>
 /// <param name='result'>
 /// Result.
 /// </param>
 /// <param name='error'>
 /// Error.
 /// </param>
 public MailCompletedEventArgs(MFMailComposeResult result, NSError error)
 {
     this.result = result;
     this.error = error;
     this.completed = (result == MFMailComposeResult.Sent);
     //			this.Result = result;
     //			this.Error = error;
     //			this.Completed = (result == MFMailComposeResult.Sent);
 }
        public override void DidCompleteWithError(NSUrlSession session, NSUrlSessionTask task, NSError error)
        {
            if (error != null)
            {
                TaskDescription description = JsonParser.ParseTaskDescription(task.TaskDescription).Result;

                OnDownloadCompleted("", task.TaskDescription ?? "", error.LocalizedDescription);
            }
        }
		/// <Docs>To be added.</Docs>
		/// <summary>
		/// Application developers should override this method to return the document data to be saved.
		/// </summary>
		/// <remarks>(More documentation for this node is coming)</remarks>
		/// <returns>The for type.</returns>
		/// <param name="typeName">Type name.</param>
		/// <param name="outError">Out error.</param>
		public override NSObject ContentsForType (string typeName, out NSError outError)
		{
			// Clear the error state
			outError = null;

			// Convert the contents to a NSData object and return it
			NSData docData = _dataModel.Encode(NSStringEncoding.UTF8);
			return docData;
		}
 public override void Failed (CLLocationManager manager, NSError error)
 {
     if (error.Code == (int)CLError.Denied) {
         Console.WriteLine ("Access to location services denied");
         
         manager.StopUpdatingLocation ();
         manager.Delegate = null;
     }
 }
 //public override void PaymentQueueRestoreCompletedTransactionsFinished (SKPaymentQueue queue)
 //{
 //    // Restore succeeded
 //    Console.WriteLine(" ** RESTORE PaymentQueueRestoreCompletedTransactionsFinished ");
 //    if (CompleteTransactionCallback != null)
 //    {
 //        CompleteTransactionCallback("", true);
 //    }
 //}
 public override void RestoreCompletedTransactionsFailedWithError(SKPaymentQueue queue, NSError error)
 {
     // Restore failed somewhere...
     Console.WriteLine(" ** RESTORE RestoreCompletedTransactionsFailedWithError " + error.LocalizedDescription);
     if (CompleteTransactionCallback != null)
     {
         CompleteTransactionCallback(error.LocalizedDescription, false);
     }
 }
		public void DidFinishProcessingLivePhotoMovie (AVCapturePhotoOutput captureOutput, NSUrl outputFileUrl, CMTime duration, CMTime photoDisplayTime, AVCaptureResolvedPhotoSettings resolvedSettings, NSError error)
		{
			if (error != null) {
				Console.WriteLine ($"Error processing live photo companion movie: {error.LocalizedDescription})");
				return;
			}

			livePhotoCompanionMovieUrl = outputFileUrl;
		}
Beispiel #28
0
		/// <summary>
		/// Called when [update].
		/// </summary>
		/// <param name="gyroData">The gyro data.</param>
		/// <param name="error">The error.</param>
		private void OnUpdate(CMGyroData gyroData, NSError error)
		{
			if (error != null)
			{
				this.readingAvailable.Invoke(
					this,
					new Vector3(gyroData.RotationRate.x, gyroData.RotationRate.y, gyroData.RotationRate.z));
			}
		}
        public int BtRead(ref byte[] data, double timeout, out NSError error)
        {
            IntPtr ptr = Marshal.AllocHGlobal (data.Length);
            int result = BtRead_ (ref ptr, data.Length, timeout, out error);
            Marshal.Copy (ptr, data, 0, data.Length);
            Marshal.FreeHGlobal(ptr);

            return result;
        }
        public bool BtWrite(byte[] data, out NSError error)
        {
            IntPtr ptr = Marshal.AllocHGlobal (data.Length);
            Marshal.Copy(data, 0, ptr, data.Length);
            bool success = BtWrite_ (ptr, data.Length, out error);
            Marshal.FreeHGlobal(ptr);

            return success;
        }
Beispiel #31
0
            private MvxLocationErrorCode ToMvxLocationErrorCode(CLLocationManager manager, NSError error, CLRegion region = null)
            {
                var errorType = (CLError)(int)error.Code;

                if (errorType == CLError.Denied)
                {
                    return(MvxLocationErrorCode.PermissionDenied);
                }

                if (errorType == CLError.Network)
                {
                    return(MvxLocationErrorCode.Network);
                }

                if (errorType == CLError.DeferredCanceled)
                {
                    return(MvxLocationErrorCode.Canceled);
                }

                return(MvxLocationErrorCode.ServiceUnavailable);
            }
Beispiel #32
0
 /// <summary>
 /// 注册token失败
 /// </summary>
 /// <param name="application"></param>
 /// <param name="error"></param>
 public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
 {
     new UIAlertView("注册通知失败", error.LocalizedDescription, null, "OK", null).Show();
 }
Beispiel #33
0
 public override void DidFailProvisionalNavigation(WKWebView webView, WKNavigation navigation, NSError error)
 {
     // If navigation fails, this gets called
     Console.WriteLine("DidFailProvisionalNavigation" + error.ToString());
 }
Beispiel #34
0
        public void getTransactionInfo(bool payWithPayPal, Action completionHandler)
        {
            //#internal_code_section_start
            var merchantURL = new String(@"");

            if (payWithPayPal)
            {
                merchantURL = @"https://api-gateway-pp.nets.eu/pia/merchantdemo/v2/payment/493809/register";
            }
            else
            {
                merchantURL = @"https://api-gateway-pp.nets.eu/pia/test/merchantdemo/v2/payment/12002835/register";
            }

            //#internal_code_section_end

            /*#external_code_section_start
             * var merchantURL = @"YOUR MERCHANT BACKEND URL HERE";
             #external_code_section_end*/

            NSMutableDictionary jsonDictionary = new NSMutableDictionary();

            if (payWithPayPal == false)
            {
                NSMutableDictionary amount = new NSMutableDictionary();
                amount.SetValueForKey(new NSNumber(1000), new NSString(@"totalAmount"));
                amount.SetValueForKey(new NSNumber(200), new NSString(@"vatAmount"));
                amount.SetValueForKey(new NSString(@"EUR"), new NSString(@"currencyCode"));

                jsonDictionary.SetValueForKey(amount, new NSString(@"amount"));
            }
            else
            {
                NSMutableDictionary amount = new NSMutableDictionary();
                amount.SetValueForKey(new NSNumber(1000), new NSString(@"totalAmount"));
                amount.SetValueForKey(new NSNumber(0), new NSString(@"vatAmount"));
                amount.SetValueForKey(new NSString(@"DKK"), new NSString(@"currencyCode"));

                jsonDictionary.SetValueForKey(amount, new NSString(@"amount"));
            }

            jsonDictionary.SetValueForKey(new NSString(@"000011"), new NSString(@"customerId"));
            jsonDictionary.SetValueForKey(new NSString(@"PiaSDK-iOS-xamarin"), new NSString(@"orderNumber"));
            jsonDictionary.SetValueForKey(new NSNumber(true), new NSString(@"storeCard"));

            if (payWithPayPal)
            {
                NSMutableDictionary method = new NSMutableDictionary();
                method.SetValueForKey(new NSString(@"PayPal"), new NSString(@"id"));
                method.SetValueForKey(new NSString(@"PayPal"), new NSString(@"displayName"));
                method.SetValueForKey(new NSNumber(0), new NSString(@"fee"));
                jsonDictionary.SetValueForKey(method, new NSString(@"method"));
            }

            if (isPayingWithToken)
            {
                // Make sure you have a saved card in your backend.
                NSMutableDictionary method = new NSMutableDictionary();
                method.SetValueForKey(new NSString(@"EasyPayment"), new NSString(@"id"));
                method.SetValueForKey(new NSString(@"Easy Payment"), new NSString(@"displayName"));
                method.SetValueForKey(new NSNumber(0), new NSString(@"fee"));
                jsonDictionary.SetValueForKey(method, new NSString(@"method"));
                jsonDictionary.SetValueForKey(new NSString(@"492500******0004"), new NSString(@"cardId"));
            }

            if (NSJsonSerialization.IsValidJSONObject(jsonDictionary))
            {
                NSError             error1   = null;
                NSData              jsonData = NSJsonSerialization.Serialize(jsonDictionary, NSJsonWritingOptions.PrettyPrinted, out error1);
                NSUrl               url      = new NSUrl(merchantURL);
                NSMutableUrlRequest request  = new NSMutableUrlRequest(url, NSUrlRequestCachePolicy.UseProtocolCachePolicy, 30.0);
                request.HttpMethod = @"POST";
                NSMutableDictionary dic = new NSMutableDictionary();
                dic.Add(new NSString("Content-Type"), new NSString("application/json;charset=utf-8;version=2.0"));
                dic.Add(new NSString("Accept"), new NSString("application/json;charset=utf-8;version=2.0"));
                request.Headers = dic;
                request.Body    = jsonData;

                NSError          error2  = null;
                NSUrlSession     session = NSUrlSession.SharedSession;
                NSUrlSessionTask task    = session.CreateDataTask(request, (data, response, error) =>
                {
                    if (data.Length > 0 && error == null)
                    {
                        NSDictionary resultsDictionary = (Foundation.NSDictionary)NSJsonSerialization.Deserialize(data, NSJsonReadingOptions.MutableLeaves, out error2);
                        if (resultsDictionary[@"transactionId"] != null && resultsDictionary[@"redirectOK"] != null)
                        {
                            NSString transactionId = (Foundation.NSString)resultsDictionary[@"transactionId"];
                            NSString redirectOK    = (Foundation.NSString)resultsDictionary[@"redirectOK"];
                            transactionInfo        = new NPITransactionInfo(transactionId, redirectOK);
                        }
                        else
                        {
                            transactionInfo = null;
                        }
                        completionHandler();
                    }
                    else
                    {
                        transactionInfo = null;
                        completionHandler();
                    }
                });

                task.Resume();
            }
        }
 public void WillDispatch(SignIn signIn, NSError error)
 {
 }
Beispiel #36
0
 public override void DidFailNavigation(WKWebView webView, WKNavigation navigation, NSError error)
 {
     _webView.Get()?.OnLoadError(error);
 }
Beispiel #37
0
 public override void DidFail(HKWorkoutSession workoutSession, NSError error)
 {
     // Handle workout session failing
     RaiseFailed();
 }
Beispiel #38
0
 public override void FailedWithError(NSUrlConnection connection, NSError error)
 {
     _taskSource.SetException(new Exception(error.Description));
 }
 /// <summary>
 /// Call this from the corresponding method override in your AppDelegate.
 /// </summary>
 /// <param name="error">Associated error.</param>
 public static void FailedToRegisterForRemoteNotifications(NSError error)
 {
     MSPush.DidFailToRegisterForRemoteNotificationsWithError(error);
 }
Beispiel #40
0
 void handler(CMTime requestedTime, IntPtr imageRef, CMTime actualTime, AVAssetImageGeneratorResult result, NSError error)
 {
     handled = true;
     mre.Set();
 }
 public void FailedToRegister(NSError error)
 {
     Util.Debug("Registration failed w/ exception:'{0}'", error.Description);
 }
Beispiel #42
0
 public abstract void HypeDidFailStarting(HYP hype, NSError error);
Beispiel #43
0
 public override void MonitoringFailed(CLLocationManager manager, CLRegion region, NSError error)
 {
     _owner.SendError(ToMvxLocationErrorCode(manager, error, region));
 }
Beispiel #44
0
 public abstract void HypeDidStop(HYP hype, NSError error);
Beispiel #45
0
 public BandDistanceDataEventArgs(BandSensorDistanceData data, NSError error)
     : base(data, error)
 {
 }
Beispiel #46
0
        public void registerCallForWallets(int wallet, Action completionHandler)
        {
            //#internal_code_section_start
            var merchantURL = new String(@"https://api-gateway-pp.nets.eu/pia/test/merchantdemo/v2/payment/12002835/register");
            //#internal_code_section_end

            /*#external_code_section_start
             * var merchantURL = @"YOUR MERCHANT BACKEND URL HERE";
             #external_code_section_end*/

            NSMutableDictionary jsonDictionary = new NSMutableDictionary();
            NSMutableDictionary amount         = new NSMutableDictionary();
            NSMutableDictionary method         = new NSMutableDictionary();

            amount.SetValueForKey(new NSNumber(1000), new NSString(@"totalAmount"));
            amount.SetValueForKey(new NSNumber(200), new NSString(@"vatAmount"));
            method.SetValueForKey(new NSNumber(0), new NSString(@"fee"));
            switch (wallet)
            {
            case (int)MobileWallet.Vipps:
            {
                amount.SetValueForKey(new NSString(@"NOK"), new NSString(@"currencyCode"));
                method.SetValueForKey(new NSString(@"Vipps"), new NSString(@"id"));
                method.SetValueForKey(new NSString(@"Vipps"), new NSString(@"displayName"));
                //#internal_code_section_start
                jsonDictionary.SetValueForKey(new NSString(@"+4748059560"), new NSString(@"phoneNumber"));
                //#internal_code_section_end

                /*#external_code_section_start
                 * jsonDictionary.SetValueForKey(new NSString(@"+471111..."), new NSString(@"phoneNumber"));
                 #external_code_section_end*/
                break;
            }

            case (int)MobileWallet.Swish:
            {
                amount.SetValueForKey(new NSString(@"SEK"), new NSString(@"currencyCode"));
                method.SetValueForKey(new NSString(@"SwishM"), new NSString(@"id"));
                method.SetValueForKey(new NSString(@"Swish"), new NSString(@"displayName"));
                break;
            }

            default: break;
            }

            jsonDictionary.SetValueForKey(amount, new NSString(@"amount"));
            jsonDictionary.SetValueForKey(method, new NSString(@"method"));
            jsonDictionary.SetValueForKey(new NSString(@"000011"), new NSString(@"customerId"));
            jsonDictionary.SetValueForKey(new NSString(@"PiaSDK-iOS-xamarin"), new NSString(@"orderNumber"));
            jsonDictionary.SetValueForKey(new NSNumber(false), new NSString(@"storeCard"));


            //#internal_code_section_start
            jsonDictionary.SetValueForKey(new NSString("eu.nets.pia.xamarin://piasdk"), new NSString(@"redirectUrl"));
            //#internal_code_section_end

            /*#external_code_section_start
             * jsonDictionary.SetValueForKey(new NSString("YOUR_APP_SCHEME_URL://piasdk"), new NSString(@"redirectUrl"));
             #external_code_section_end*/



            if (NSJsonSerialization.IsValidJSONObject(jsonDictionary))
            {
                NSError             error1   = null;
                NSData              jsonData = NSJsonSerialization.Serialize(jsonDictionary, NSJsonWritingOptions.PrettyPrinted, out error1);
                NSUrl               url      = new NSUrl(merchantURL);
                NSMutableUrlRequest request  = new NSMutableUrlRequest(url, NSUrlRequestCachePolicy.UseProtocolCachePolicy, 30.0);
                request.HttpMethod = @"POST";
                NSMutableDictionary dic = new NSMutableDictionary();
                dic.Add(new NSString("Content-Type"), new NSString("application/json;charset=utf-8;version=2.0"));
                dic.Add(new NSString("Accept"), new NSString("application/json;charset=utf-8;version=2.0"));
                request.Headers = dic;
                request.Body    = jsonData;

                NSError          error2  = null;
                NSUrlSession     session = NSUrlSession.SharedSession;
                NSUrlSessionTask task    = session.CreateDataTask(request, (data, response, error) =>
                {
                    if (data.Length > 0 && error == null)
                    {
                        NSDictionary resultsDictionary = (Foundation.NSDictionary)NSJsonSerialization.Deserialize(data, NSJsonReadingOptions.MutableLeaves, out error2);
                        if (resultsDictionary[@"transactionId"] != null && resultsDictionary[@"walletUrl"] != null)
                        {
                            NSString transactionId = (Foundation.NSString)resultsDictionary[@"transactionId"];
                            NSString walletURL     = (Foundation.NSString)resultsDictionary[@"walletUrl"];
                            transactionInfo        = new NPITransactionInfo(walletURL);
                        }
                        else
                        {
                            transactionInfo = null;
                        }
                        completionHandler();
                    }
                    else
                    {
                        transactionInfo = null;
                        completionHandler();
                    }
                });

                task.Resume();
            }
        }
Beispiel #47
0
 public override void Failed(CLLocationManager manager, NSError error)
 {
     _owner.SendError(ToMvxLocationErrorCode(manager, error));
 }
 private void MagnetometerHandler(CMDeviceMotion magnetometerData, NSError error)
 {
     readingChanged(magnetometerData, error);
 }
 public void WillDispatch(SignIn signIn, NSError error)
 {
     //myActivityIndicator.StopAnimating();
 }
 public void DidDisconnect(SignIn signIn, GoogleUser user, NSError error)
 {
     // Perform any operations when the user disconnects from app here.
 }
Beispiel #51
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Initializing the energy module.
            frame = UIScreen.MainScreen.ApplicationFrame;
            frame = new CGRect(frame.X,
                               frame.Y + NavigationController.NavigationBar.Frame.Size.Height,
                               frame.Width,
                               frame.Height - NavigationController.NavigationBar.Frame.Size.Height);

            anylineEnergyView = new AnylineEnergyModuleView(frame);

            error   = null;
            success = anylineEnergyView.SetupWithLicenseKey(licenseKey, this.Self, out error);
            if (!success)
            {
                (alert = new UIAlertView("Error", error.DebugDescription, null, "OK", null)).Show();
            }

            //we'll stop scanning manually
            anylineEnergyView.CancelOnResult = false;

            // After setup is complete we add the module to the view of this view controller
            View.AddSubview(anylineEnergyView);

            anylineEnergyView.ScanMode = segmentItems.ElementAt(defaultIndex).Value;

            //we don't need a segment control for only one option:
            if (segmentItems.Count > 1)
            {
                meterTypeSegment = new UISegmentedControl(segmentItems.Keys.ToArray());

                //adjust the segmentcontrol size so all elements fit to the view
                if (meterTypeSegment.NumberOfSegments > 3)
                {
                    for (int i = 0; i < meterTypeSegment.NumberOfSegments; i++)
                    {
                        meterTypeSegment.SetWidth(View.Frame.Width / (meterTypeSegment.NumberOfSegments + 1), i);
                    }

                    meterTypeSegment.ApportionsSegmentWidthsByContent = true;
                }
                meterTypeSegment.Center = new CGPoint(View.Center.X, View.Frame.Size.Height - 40);

                meterTypeSegment.SelectedSegment = this.defaultIndex;
                meterTypeSegment.ValueChanged   += HandleSegmentChange;
                View.AddSubview(meterTypeSegment);

                selectionLabel           = new UILabel(new CGRect(meterTypeSegment.Frame.X, meterTypeSegment.Frame.Y - 35, meterTypeSegment.Frame.Width, 35));
                selectionLabel.TextColor = UIColor.White;
                selectionLabel.Text      = labelText;
                View.AddSubview(selectionLabel);

                infoLabel               = new UILabel(new CGRect(0, View.Frame.Y + NavigationController.NavigationBar.Frame.Size.Height + 13, View.Frame.Width, 35));
                infoLabel.TextColor     = UIColor.White;
                infoLabel.Text          = "";
                infoLabel.TextAlignment = UITextAlignment.Center;
                View.AddSubview(infoLabel);

                UpdateInfoLabel(anylineEnergyView.ScanMode);
            }
        }
Beispiel #52
0
        public override void DidCompleteWithError(NSUrlSession session, NSUrlSessionTask task, NSError error)
        {
            if (error == null)
            {
                return;
            }

            Console.WriteLine("DidCompleteWithError - Task: {0}, Error: {1}", task.TaskIdentifier, error);

            task.Cancel();
        }
Beispiel #53
0
        void OnRequestHandler(GraphRequestConnection connection, NSObject result, NSError error)
        {
            if (error != null || result == null)
            {
                _onLoginComplete?.Invoke(null, new Exception(error.LocalizedDescription));
            }
            else
            {
                var id         = string.Empty;
                var first_name = string.Empty;
                var email      = string.Empty;
                var last_name  = string.Empty;
                var fullname   = string.Empty;
                var url        = string.Empty;

                try
                {
                    id = result.ValueForKey(new NSString("id"))?.ToString();
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.Message);
                }

                try
                {
                    first_name = result.ValueForKey(new NSString("first_name"))?.ToString();
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.Message);
                }

                try
                {
                    email = result.ValueForKey(new NSString("email"))?.ToString();
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.Message);
                }

                try
                {
                    last_name = result.ValueForKey(new NSString("last_name"))?.ToString();
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.Message);
                }

                try
                {
                    fullname = result.ValueForKey(new NSString("name"))?.ToString();
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.Message);
                }

                try
                {
                    url = ((result.ValueForKey(new NSString("picture")) as NSDictionary).ValueForKey(new NSString("data")) as NSDictionary).ValueForKey(new NSString("url")).ToString();
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.Message);
                }
                _onLoginComplete?.Invoke(new FacebookUser(id, AccessToken.CurrentAccessToken.TokenString, first_name, last_name, fullname, email, url), null);
            }
        }
Beispiel #54
0
        bool SetupCaptureSession()
        {
            if (CameraPreviewSettings.Instance.Decoder == null)
            {
                return(false);
            }

            var started = DateTime.UtcNow;

            var availableResolutions = new List <CameraResolution>();

            var consideredResolutions = new Dictionary <NSString, CameraResolution> {
                { AVCaptureSession.Preset352x288, new CameraResolution   {
                      Width = 352, Height = 288
                  } },
                { AVCaptureSession.PresetMedium, new CameraResolution    {
                      Width = 480, Height = 360
                  } },                                                                                      //480x360
                { AVCaptureSession.Preset640x480, new CameraResolution   {
                      Width = 640, Height = 480
                  } },
                { AVCaptureSession.Preset1280x720, new CameraResolution  {
                      Width = 1280, Height = 720
                  } },
                { AVCaptureSession.Preset1920x1080, new CameraResolution {
                      Width = 1920, Height = 1080
                  } }
            };

            // configure the capture session for low resolution, change this if your code
            // can cope with more data or volume
            session = new AVCaptureSession()
            {
                SessionPreset = AVCaptureSession.Preset640x480
            };

            // create a device input and attach it to the session
            //          var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType (AVMediaType.Video);
            AVCaptureDevice captureDevice = null;
            var             devices       = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video);

            foreach (var device in devices)
            {
                captureDevice = device;
                if (CameraPreviewSettings.Instance.ScannerOptions.UseFrontCameraIfAvailable.HasValue &&
                    CameraPreviewSettings.Instance.ScannerOptions.UseFrontCameraIfAvailable.Value &&
                    device.Position == AVCaptureDevicePosition.Front)
                {
                    break; //Front camera successfully set
                }
                else if (device.Position == AVCaptureDevicePosition.Back &&
                         (!CameraPreviewSettings.Instance.ScannerOptions.UseFrontCameraIfAvailable.HasValue ||
                          !CameraPreviewSettings.Instance.ScannerOptions.UseFrontCameraIfAvailable.Value))
                {
                    break; //Back camera succesfully set
                }
            }
            if (captureDevice == null)
            {
                Console.WriteLine("No captureDevice - this won't work on the simulator, try a physical device");
                return(false);
            }

            CameraResolution resolution = null;

            // Find resolution
            // Go through the resolutions we can even consider
            foreach (var cr in consideredResolutions)
            {
                // Now check to make sure our selected device supports the resolution
                // so we can add it to the list to pick from
                if (captureDevice.SupportsAVCaptureSessionPreset(cr.Key))
                {
                    availableResolutions.Add(cr.Value);
                }
            }

            resolution = CameraPreviewSettings.Instance.ScannerOptions.GetResolution(availableResolutions);

            // See if the user selected a resolution
            if (resolution != null)
            {
                // Now get the preset string from the resolution chosen
                var preset = (from c in consideredResolutions
                              where c.Value.Width == resolution.Width &&
                              c.Value.Height == resolution.Height
                              select c.Key).FirstOrDefault();

                // If we found a matching preset, let's set it on the session
                if (!string.IsNullOrEmpty(preset))
                {
                    session.SessionPreset = preset;
                }
            }

            var input = AVCaptureDeviceInput.FromDevice(captureDevice);

            if (input == null)
            {
                Console.WriteLine("No input - this won't work on the simulator, try a physical device");
                return(false);
            }
            else
            {
                session.AddInput(input);
            }


            var startedAVPreviewLayerAlloc = PerformanceCounter.Start();

            previewLayer = new AVCaptureVideoPreviewLayer(session);

            PerformanceCounter.Stop(startedAVPreviewLayerAlloc, "Alloc AVCaptureVideoPreviewLayer took {0} ms.");

            var perf2 = PerformanceCounter.Start();

#if __UNIFIED__
            previewLayer.VideoGravity = AVLayerVideoGravity.ResizeAspectFill;
#else
            previewLayer.LayerVideoGravity = AVLayerVideoGravity.ResizeAspectFill;
#endif
            previewLayer.Frame    = new CGRect(0, 0, this.Frame.Width, this.Frame.Height);
            previewLayer.Position = new CGPoint(this.Layer.Bounds.Width / 2, (this.Layer.Bounds.Height / 2));

            layerView = new UIView(new CGRect(0, 0, this.Frame.Width, this.Frame.Height));
            layerView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
            layerView.Layer.AddSublayer(previewLayer);

            this.AddSubview(layerView);

            ResizePreview(UIApplication.SharedApplication.StatusBarOrientation);


            PerformanceCounter.Stop(perf2, "PERF: Setting up layers took {0} ms");

            var perf3 = PerformanceCounter.Start();

            session.StartRunning();

            PerformanceCounter.Stop(perf3, "PERF: session.StartRunning() took {0} ms");

            var perf4 = PerformanceCounter.Start();

            var videoSettings = NSDictionary.FromObjectAndKey(new NSNumber((int)CVPixelFormatType.CV32BGRA),
                                                              CVPixelBuffer.PixelFormatTypeKey);


            // create a VideoDataOutput and add it to the sesion
            output = new AVCaptureVideoDataOutput
            {
                WeakVideoSettings = videoSettings
            };

            // configure the output
            queue          = new DispatchQueue("CamerPreviewView"); // (Guid.NewGuid().ToString());
            outputRecorder = new DefaultOutputRecorder(resultCallback);
            output.AlwaysDiscardsLateVideoFrames = true;
            output.SetSampleBufferDelegateQueue(outputRecorder, queue);

            PerformanceCounter.Stop(perf4, "PERF: SetupCamera Finished.  Took {0} ms.");

            session.AddOutput(output);
            //session.StartRunning ();


            var perf5 = PerformanceCounter.Start();

            NSError err = null;
            if (captureDevice.LockForConfiguration(out err))
            {
                if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.ContinuousAutoFocus))
                {
                    captureDevice.FocusMode = AVCaptureFocusMode.ContinuousAutoFocus;
                }
                else if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.AutoFocus))
                {
                    captureDevice.FocusMode = AVCaptureFocusMode.AutoFocus;
                }

                if (captureDevice.IsExposureModeSupported(AVCaptureExposureMode.ContinuousAutoExposure))
                {
                    captureDevice.ExposureMode = AVCaptureExposureMode.ContinuousAutoExposure;
                }
                else if (captureDevice.IsExposureModeSupported(AVCaptureExposureMode.AutoExpose))
                {
                    captureDevice.ExposureMode = AVCaptureExposureMode.AutoExpose;
                }

                if (captureDevice.IsWhiteBalanceModeSupported(AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance))
                {
                    captureDevice.WhiteBalanceMode = AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance;
                }
                else if (captureDevice.IsWhiteBalanceModeSupported(AVCaptureWhiteBalanceMode.AutoWhiteBalance))
                {
                    captureDevice.WhiteBalanceMode = AVCaptureWhiteBalanceMode.AutoWhiteBalance;
                }

                if (UIDevice.CurrentDevice.CheckSystemVersion(7, 0) && captureDevice.AutoFocusRangeRestrictionSupported)
                {
                    captureDevice.AutoFocusRangeRestriction = AVCaptureAutoFocusRangeRestriction.Near;
                }

                if (captureDevice.FocusPointOfInterestSupported)
                {
                    captureDevice.FocusPointOfInterest = new PointF(0.5f, 0.5f);
                }

                if (captureDevice.ExposurePointOfInterestSupported)
                {
                    captureDevice.ExposurePointOfInterest = new PointF(0.5f, 0.5f);
                }

                captureDevice.UnlockForConfiguration();
            }
            else
            {
                Logger.Log("Failed to Lock for Config: " + err.Description);
            }

            PerformanceCounter.Stop(perf5, "PERF: Setup Focus in {0} ms.");

            return(true);
        }
 public static BLEErrorCode ToShared(this NSError error)
 => (BLEErrorCode)(int)error.Code;
Beispiel #56
0
        public override async void DidCompleteWithError(NSUrlSession session, NSUrlSessionTask task, NSError error)
        {
            try
            {
                var transfer = task.FromNative();

                if (task.State != NSUrlSessionTaskState.Canceling && error != null)
                {
                    Log.Write(transfer.Exception, ("HttpTransfer", transfer.Identifier));
                    await this.tdelegate.OnError(transfer, transfer.Exception);
                }
                this.onEvent.OnNext(transfer);
            }
            catch (Exception ex)
            {
                Log.Write(ex);
            }
        }
 public void DidComplete(ASAuthorizationController controller, NSError error)
 => tcsCredential?.TrySetException(new Exception(error.LocalizedDescription));
 public override void DidFinishReceivingResource(MCSession session, string resourceName, MCPeerID formPeer, NSUrl localUrl, NSError error)
 {
     error = null;
 }
Beispiel #59
0
 private void AccelerometerHandler(CMAccelerometerData data, NSError error)
 {
     readingChanged(data, error);
 }
 public virtual void Screenlet(AssetDisplayScreenlet screenlet, NSError error)
 {
     Console.WriteLine($"Asset display error: {error.DebugDescription}");
 }