public OperationResult <double> GetDistanceFrom(Position referencePosition) { if (referencePosition == null) { return(OperationResult <double> .AsFailure("Invalid reference position specified")); } if (_lastPosition == null) { return(OperationResult <double> .AsFailure("Current position not available")); } float[] results = new float[1]; try { Android.Locations.Location.DistanceBetween(referencePosition.Latitude, referencePosition.Longitude, _lastPosition.Latitude, _lastPosition.Longitude, results); } catch (IllegalArgumentException e) { return(OperationResult <double> .AsFailure(e)); } if (results != null && results.Length > 0) { return(OperationResult <double> .AsSuccess(results[0])); } else { return(OperationResult <double> .AsFailure("Could not calculate distance")); } }
/// <summary> /// Start listening to location changes /// </summary> /// <param name="minTime">Minimum interval in milliseconds</param> /// <param name="minDistance">Minimum distance in meters</param> /// <param name="includeHeading">Include heading information</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// minTime /// or /// minDistance /// </exception> /// <exception cref="System.InvalidOperationException">This Geolocator is already listening</exception> public OperationResult StartListening(uint minTime, double minDistance, double desiredAccurancy = 0, bool includeHeading = false) { if (IsListening) { return(OperationResult.AsFailure("Already listening")); } if (minTime < 0) { return(OperationResult.AsFailure(new ArgumentOutOfRangeException(nameof(minTime)))); } if (minDistance < 0) { return(OperationResult.AsFailure(new ArgumentOutOfRangeException(nameof(minDistance)))); } _desiredAccuracy = desiredAccurancy; _listener = new GeolocationContinuousListener(_manager, TimeSpan.FromMilliseconds(minTime), _providers); _listener.PositionChanged += OnListenerPositionChanged; _listener.PositionError += OnListenerPositionError; var looper = Looper.MyLooper() ?? Looper.MainLooper; for (var i = 0; i < _providers.Length; ++i) { _manager.RequestLocationUpdates(_providers[i], minTime, (float)minDistance, _listener, looper); } return(OperationResult.AsSuccess()); }
public async Task <OperationResult> SnapStillImage() { AVCaptureConnection connection = _stillImageOutput.ConnectionFromMediaType(AVMediaType.Video); var previewLayer = (AVCaptureVideoPreviewLayer)PreviewLayer; // Update the orientation on the still image output video connection before capturing. connection.VideoOrientation = previewLayer.Connection.VideoOrientation; // Flash set to Auto for Still Capture. _videoDeviceInput.Device.SetFlashMode(AVCaptureFlashMode.Auto); // Capture a still image. try { var imageDataSampleBuffer = await _stillImageOutput.CaptureStillImageTaskAsync(connection); // The sample buffer is not retained. Create image data before saving the still image to the photo library asynchronously. NSData imageData = AVCaptureStillImageOutput.JpegStillToNSData(imageDataSampleBuffer); if (OnImageSnapped != null) { OnImageSnapped(imageData); } return(OperationResult.AsSuccess()); } catch (NSErrorException ex) { return(OperationResult.AsFailure(ex)); } }
public Task <OperationResult> StartRecording(string filePath) { TaskCompletionSource <OperationResult> tcs = new TaskCompletionSource <OperationResult>(); if (_movieFileOutput.Recording) { tcs.SetResult(OperationResult.AsFailure("Recording already in progress")); } else { if (UIDevice.CurrentDevice.IsMultitaskingSupported) { // Setup background task. This is needed because the IAVCaptureFileOutputRecordingDelegate.FinishedRecording // callback is not received until AVCam returns to the foreground unless you request background execution time. // This also ensures that there will be time to write the file to the photo library when AVCam is backgrounded. // To conclude this background execution, UIApplication.SharedApplication.EndBackgroundTask is called in // IAVCaptureFileOutputRecordingDelegate.FinishedRecording after the recorded file has been saved. _backgroundRecordingID = UIApplication.SharedApplication.BeginBackgroundTask(null); } // Update the orientation on the movie file output video connection before starting recording. AVCaptureConnection connection = _movieFileOutput.ConnectionFromMediaType(AVMediaType.Video); connection.VideoOrientation = PreviewLayer.Connection.VideoOrientation; // Turn OFF flash for video recording. _videoDeviceInput.Device.SetFlashMode(AVCaptureFlashMode.Off); // Start recording to a temporary file. _movieFileOutput.StartRecordingToOutputFile(new NSUrl(filePath, false), this); tcs.SetResult(OperationResult.AsSuccess()); } return(tcs.Task); }
public OperationResult <double> GetDistanceBetween(Position firstPosition, Position secondPosition) { if (firstPosition == null || secondPosition == null) { return(OperationResult <double> .AsFailure("Invalid positions specified")); } float[] results = new float[1]; try { Android.Locations.Location.DistanceBetween(firstPosition.Latitude, firstPosition.Longitude, secondPosition.Latitude, secondPosition.Longitude, results); } catch (IllegalArgumentException e) { return(OperationResult <double> .AsFailure(e)); } if (results != null && results.Length > 0) { return(OperationResult <double> .AsSuccess(results[0])); } else { return(OperationResult <double> .AsFailure("Could not calculate distance")); } }
public OperationResult Initialize(string audioFilePath, float sampleRate = 44100, int channels = 2, int bitDepth = 16) { if (string.IsNullOrEmpty(audioFilePath)) { return(OperationResult <double> .AsFailure("Invalid audio file path specified")); } _audioFilePath = audioFilePath; if (_recorder == null) { _recorder = new MediaRecorder(); _recorder.SetAudioSource(AudioSource.Mic); _recorder.SetOutputFormat(OutputFormat.ThreeGpp); _recorder.SetAudioEncoder(AudioEncoder.AmrNb); } else { if (File.Exists(_audioFilePath)) { File.Delete(_audioFilePath); } } File.Create(audioFilePath); _recorder.SetOutputFile(audioFilePath); _recorder.Prepare(); return(OperationResult.AsSuccess()); }
/// <summary> /// Set the device's focus settings /// </summary> /// <returns><see cref="T:ChilliSource.Mobile.Core.OperationResult"/> instance indicating the outcome of the operation</returns> /// <param name="videoDeviceInput">Video device input.</param> /// <param name="focusMode">Focus mode.</param> /// <param name="exposureMode">Exposure mode.</param> /// <param name="pointOfInterest">Point of interest</param> /// <param name="monitorSubjectAreaChange">If set to <c>true</c> monitor subject area change.</param> public static OperationResult UpdateFocus(this AVCaptureDeviceInput videoDeviceInput, AVCaptureFocusMode focusMode, AVCaptureExposureMode exposureMode, CGPoint pointOfInterest, bool monitorSubjectAreaChange) { if (videoDeviceInput == null) { return(OperationResult.AsFailure("device input is null")); } AVCaptureDevice device = videoDeviceInput.Device; NSError error; if (device.LockForConfiguration(out error)) { if (device.FocusPointOfInterestSupported && device.IsFocusModeSupported(focusMode)) { device.FocusPointOfInterest = pointOfInterest; device.FocusMode = focusMode; } if (device.ExposurePointOfInterestSupported && device.IsExposureModeSupported(exposureMode)) { device.ExposurePointOfInterest = pointOfInterest; device.ExposureMode = exposureMode; } device.SubjectAreaChangeMonitoringEnabled = monitorSubjectAreaChange; device.UnlockForConfiguration(); return(OperationResult.AsSuccess()); } else { return(OperationResult.AsFailure(string.Format("Could not lock device for configuration: {0}", error))); } }
public OperationResult <double> Initialize(string audioFilePath) { if (string.IsNullOrEmpty(audioFilePath) || !File.Exists(audioFilePath)) { return(OperationResult <double> .AsFailure("Invalid audio file path specified")); } var audioSession = AVAudioSession.SharedInstance(); var error = audioSession.SetCategory(AVAudioSessionCategory.Playback); if (error != null) { return(OperationResult <double> .AsFailure(error.LocalizedDescription)); } error = audioSession.SetActive(true); if (error != null) { return(OperationResult <double> .AsFailure(error.LocalizedDescription)); } NSUrl audioUrl = NSUrl.FromFilename(audioFilePath); if (_player != null) { _player.FinishedPlaying -= DidFinishPlaying; _player.Dispose(); _player = null; } _player = AVAudioPlayer.FromUrl(audioUrl); _player.NumberOfLoops = 0; _player.FinishedPlaying += DidFinishPlaying; return(OperationResult <double> .AsSuccess(_player.Duration)); }
/// <summary> /// Performs vibration animation /// </summary> /// <returns>Returns an instance of <see cref="OperationResult"/> that represents the outcome of the animation /// and stores a <c>finalValue</c> representing the completed state of the animation.</returns> public override Task <OperationResult <double> > PerformAnimation() { AnimationTaskCompletionSource = new TaskCompletionSource <OperationResult <double> >(); _repeatCount = 0; Animation.Commit(Control, AnimationId, length: (uint)GetVibrateDuration(), finished: (finalValue, wasCancelled) => { if (_repeatCount == RepeatCount) { Control.TranslationX = 0; AnimationTaskCompletionSource.SetResult(OperationResult <double> .AsSuccess(finalValue)); } else { Control.TranslationX = -GetVibrateXChange(); } if (wasCancelled) { Control.TranslationX = 0; AnimationTaskCompletionSource.SetResult(OperationResult <double> .AsCancel()); } }, repeat: () => ++ _repeatCount < RepeatCount); return(AnimationTaskCompletionSource.Task); }
/// <summary> /// Invokes places search webservice /// <param name="searchString">Search string</param> /// <param name="request">Autocomplete request specifying additional components in the search Url to be generated</param> /// <returns>Place result with predictions</returns> /// </summary> public async Task <OperationResult <PlaceResponse> > SearchAsync(string searchString, AutocompleteRequest request) { if (string.IsNullOrWhiteSpace(searchString)) { return(OperationResult <PlaceResponse> .AsFailure("PlaceId cannot be empty")); } var url = _urlFactory.BuildSearchUrl(searchString, request); using (var client = new HttpClient()) { AcceptJsonResponse(client); var response = await client.GetAsync(url).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { return(OperationResult <PlaceResponse> .AsFailure(response.ReasonPhrase)); } var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); var result = JsonConvert.DeserializeObject <PlaceResponse>(content); return(OperationResult <PlaceResponse> .AsSuccess(result)); } }
public OperationResult <byte[]> ResizeImage(string sourcePath, float maxWidth, float maxHeight) { if (!File.Exists(sourcePath)) { return(OperationResult <byte[]> .AsFailure("Source file not found")); } var extension = Path.GetExtension(sourcePath).ToLower(); UIImage sourceImage = UIImage.FromFile(sourcePath); var resultImage = sourceImage.Resize(maxWidth, maxHeight); if (extension.Contains("png")) { return(OperationResult <byte[]> .AsSuccess(resultImage.AsPNG().ToArray())); } else if (extension.Contains("jpg") || extension.Contains("jpeg")) { return(OperationResult <byte[]> .AsSuccess(resultImage.AsJPEG().ToArray())); } else { return(OperationResult <byte[]> .AsFailure("Extension not supported")); } }
public Task <OperationResult <string> > FetchDeferredAppLink() { var tcs = new TaskCompletionSource <OperationResult <string> >(); AppLinkUtility.FetchDeferredAppLink((url, error) => { if (error != null) { tcs.SetResult(OperationResult <string> .AsFailure(error.LocalizedDescription)); } else { if (url == null) { tcs.SetResult(OperationResult <string> .AsFailure("Returned Url is null")); } else { tcs.SetResult(OperationResult <string> .AsSuccess(url.ToString())); } } }); return(tcs.Task); }
public OperationResult <double> GetVideoDuration(string filePath) { var url = NSUrl.CreateFileUrl(filePath, false, null); var asset = AVAsset.FromUrl(url); return(OperationResult <double> .AsSuccess(asset.Duration.Seconds)); }
public OperationResult <Stream> GetFirstVideoFrame(string filePath) { var url = NSUrl.CreateFileUrl(filePath, false, null); var asset = new AVUrlAsset(url); var imageGenerator = new AVAssetImageGenerator(asset); imageGenerator.AppliesPreferredTrackTransform = true; CMTime actualTime; NSError error; var cgImage = imageGenerator.CopyCGImageAtTime(new CMTime(0, 1), out actualTime, out error); if (error != null) { return(OperationResult <Stream> .AsFailure(error.ToString())); } if (cgImage != null) { return(OperationResult <Stream> .AsSuccess(new UIImage(cgImage).AsJPEG().AsStream())); } else { return(OperationResult <Stream> .AsFailure("Image generation failed")); } }
public Task <OperationResult <string> > PresentVideoEditor(string videoPath, double maxDuration) { var tcs = new TaskCompletionSource <OperationResult <string> >(); var videoEditor = new UIVideoEditorController(); videoEditor.VideoPath = videoPath; videoEditor.VideoMaximumDuration = maxDuration; videoEditor.VideoQuality = UIImagePickerControllerQualityType.High; videoEditor.Failed += (object sender, NSErrorEventArgs e) => { videoEditor.DismissModalViewController(true); tcs.SetResult(OperationResult <string> .AsFailure(e.Error.LocalizedDescription)); }; videoEditor.UserCancelled += (object sender, EventArgs e) => { videoEditor.DismissModalViewController(true); tcs.SetResult(OperationResult <string> .AsCancel()); }; videoEditor.Saved += (object sender, UIPathEventArgs e) => { tcs.SetResult(OperationResult <string> .AsSuccess(e.Path)); videoEditor.DismissModalViewController(true); }; NavigationHelper.GetActiveViewController().PresentViewController(videoEditor, true, null); return(tcs.Task); }
/// <summary> /// Invokes <see cref="SearchAsync(string, AutocompleteRequest)"/> with the given <paramref name="autocomleteRequest"/> and caches the results /// <param name="input">Search string</param> /// <param name="request">Autocomplete request specifying additional components in the search Url to be generated</param> /// </summary> public async Task <OperationResult <PlaceResponse> > AutocompleteAsync(string input, AutocompleteRequest autocomleteRequest) { //Get cached results var result = _cachingProvider.GetAutocompleteResult(input); if (result != null) { return(OperationResult <PlaceResponse> .AsSuccess(result)); } var searchResult = await SearchAsync(input, new AutocompleteRequest { Region = "au" }) .ContinueWith(response => { if (response.Result == null) { return(OperationResult <PlaceResponse> .AsFailure("Search response result is null")); } return(response.Result); }) .ConfigureAwait(false); if (searchResult.IsSuccessful) { _cachingProvider.StoreAutocompleteResult(input, searchResult.Result); } return(searchResult); }
/// <summary> /// Invokes places detail webservice to download detail info about a place identified by <paramref name="prediction"/>.PlaceId /// <param name="prediction">Search prediction</param> /// <returns>The place details</returns> /// </summary> public Task <OperationResult <DetailsResponse> > GetPlaceDetails(Prediction prediction) { if (string.IsNullOrWhiteSpace(prediction.PlaceId)) { Task.Run(() => { return(OperationResult <DetailsResponse> .AsFailure("PlaceId cannot be empty")); }); } var url = _urlFactory.BuildDetailsUrl(prediction.PlaceId); using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("Content-Type", "application/json;charset=utf-8"); return(client.GetStringAsync(url) .ContinueWith(response => { var detailsResult = JsonConvert.DeserializeObject <DetailsResponse>(response.Result); if (detailsResult.Result.Prediction != null) { detailsResult.Result.Prediction = prediction.Description; } return OperationResult <DetailsResponse> .AsSuccess(detailsResult); })); } }
/// <summary> /// Invokes <see cref="SearchAsync(string, AutocompleteRequest)"/> with the given <paramref name="autocomleteRequest"/> and caches the results /// <param name="input">Search string</param> /// <param name="request">Autocomplete request specifying additional components in the search Url to be generated</param> /// </summary> public async Task <OperationResult <PlaceResponse> > AutocompleteAsync(string input, AutocompleteRequest autocomleteRequest = null) { //Get cached results var result = _cachingProvider.GetAutocompleteResult(input); if (result != null) { return(OperationResult <PlaceResponse> .AsSuccess(result)); } OperationResult <PlaceResponse> searchResult; if (autocomleteRequest != null) { searchResult = await SearchAsync(input, autocomleteRequest); } else { searchResult = await SearchAsync(input, new AutocompleteRequest() { Region = "au" }); } if (!searchResult.IsSuccessful) { return(OperationResult <PlaceResponse> .AsFailure("Search response result is null")); } _cachingProvider.StoreAutocompleteResult(input, searchResult.Result); return(searchResult); }
/// <summary> /// Invokes places detail webservice to download detail info about a place identified by <paramref name="prediction"/>.PlaceId /// <param name="prediction">Search prediction</param> /// <returns>The place details</returns> /// </summary> public async Task <OperationResult <DetailsResponse> > GetPlaceDetails(Prediction prediction) { if (string.IsNullOrWhiteSpace(prediction.PlaceId)) { return(OperationResult <DetailsResponse> .AsFailure("PlaceId cannot be empty")); } var url = _urlFactory.BuildDetailsUrl(prediction.PlaceId); using (var client = new HttpClient()) { AcceptJsonResponse(client); var response = await client.GetAsync(url).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { return(OperationResult <DetailsResponse> .AsFailure(response.ReasonPhrase)); } var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); var detailsResult = JsonConvert.DeserializeObject <DetailsResponse>(content); if (detailsResult.Status == GoogleApiResponseStatus.Ok && detailsResult.Result.Prediction != null) { detailsResult.Result.Prediction = prediction.Description; } return(OperationResult <DetailsResponse> .AsSuccess(detailsResult)); } }
public Task <OperationResult> PerformBiometricAuthentication(string promptText) { var tcs = new TaskCompletionSource <OperationResult>(); var context = new LAContext(); NSError authError; var message = new NSString(promptText); if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out authError)) { var replyHandler = new LAContextReplyHandler((success, error) => { if (success) { tcs.SetResult(OperationResult.AsSuccess()); } else { tcs.SetResult(OperationResult.AsFailure((error as NSError).LocalizedDescription)); } }); // This starts the authentication dialog. context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, message, replyHandler); } return(tcs.Task); }
/// <summary> /// Sets the device's frame rate /// </summary> /// <returns><see cref="T:ChilliSource.Mobile.Core.OperationResult"/> instance indicating the outcome of the operation</returns> /// <param name="device">Device.</param> /// <param name="frameRate">Frame rate.</param> /// <param name="timeValue">Time value.</param> public static OperationResult SetFrameRate(this AVCaptureDevice device, int frameRate, int timeValue = 1) { NSError error = null; if (!device.LockForConfiguration(out error)) { return(OperationResult.AsFailure(error?.LocalizedDescription ?? "Could not lock configuration")); } double epsilon = 0.00000001; bool frameRateSet = false; foreach (var range in device.ActiveFormat.VideoSupportedFrameRateRanges) { if (range.MinFrameRate <= frameRate + epsilon && range.MaxFrameRate >= frameRate - epsilon) { device.ActiveVideoMaxFrameDuration = new CoreMedia.CMTime(timeValue, frameRate); device.ActiveVideoMinFrameDuration = new CoreMedia.CMTime(timeValue, frameRate); frameRateSet = true; break; } } device.UnlockForConfiguration(); return(frameRateSet ? OperationResult.AsSuccess() : OperationResult.AsFailure("Frame rate is not supported")); }
public override void UpdatedLocation(CLLocationManager manager, CLLocation newLocation, CLLocation oldLocation) { if (newLocation.HorizontalAccuracy < 0) { return; } if (_hasLocation && newLocation.HorizontalAccuracy > _position.Accuracy) { return; } _position.Accuracy = newLocation.HorizontalAccuracy; _position.Altitude = newLocation.Altitude; _position.AltitudeAccuracy = newLocation.VerticalAccuracy; _position.Latitude = newLocation.Coordinate.Latitude; _position.Longitude = newLocation.Coordinate.Longitude; _position.Speed = newLocation.Speed; _position.Timestamp = new DateTimeOffset((DateTime)newLocation.Timestamp); _hasLocation = true; if ((!_includeHeading || _hasHeading) && _position.Accuracy <= _desiredAccuracy) { _tcs.TrySetResult(OperationResult <Position> .AsSuccess(new Position(_position))); StopListening(); } }
public async Task OnSuccessAsync_ShouldBeCalled_WhenReturnsSuccessResult() { var hasSuccessExecuted = false; var hasFailureExecuted = false; var hasAlwaysExecuted = false; var result = await Task.FromResult(OperationResult <string> .AsSuccess("ok")) .OnSuccessAsync((r) => { hasSuccessExecuted = true; return(Task.FromResult(OperationResult <string> .AsSuccess("ok"))); }) .OnFailureAsync(() => { hasFailureExecuted = true; return(Task.Delay(0)); }) .AlwaysAsync(() => { hasAlwaysExecuted = true; return(Task.Delay(0)); }); Assert.True(hasSuccessExecuted); Assert.False(hasFailureExecuted); Assert.True(hasAlwaysExecuted); Assert.True(result.IsSuccessful); Assert.Equal("ok", result.Result); }
private void Finish(Android.Locations.Location location) { var position = new Position(); if (location.HasAccuracy) { position.Accuracy = location.Accuracy; } if (location.HasAltitude) { position.Altitude = location.Altitude; } if (location.HasBearing) { position.Heading = location.Bearing; } if (location.HasSpeed) { position.Speed = location.Speed; } position.Longitude = location.Longitude; position.Latitude = location.Latitude; position.Timestamp = LocationService.GetTimestamp(location); _finishedCallback?.Invoke(); _tcs.TrySetResult(OperationResult <Position> .AsSuccess(position)); }
//needed for sharing to Facebook public Task <OperationResult <string> > LegacySaveVideo(string videoPath) { var tcs = new TaskCompletionSource <OperationResult <string> >(); if (string.IsNullOrEmpty(videoPath) || !File.Exists(videoPath)) { tcs.SetResult(OperationResult <string> .AsFailure("Invalid video file path specified")); return(tcs.Task); } var url = NSUrl.CreateFileUrl(videoPath, false, null); var library = new ALAssetsLibrary(); library.WriteVideoToSavedPhotosAlbum(url, (resultUrl, error) => { if (error == null) { tcs.SetResult(OperationResult <string> .AsSuccess(resultUrl.AbsoluteString)); } else { tcs.SetResult(OperationResult <string> .AsFailure(error.LocalizedDescription)); } }); return(tcs.Task); }
public Task <OperationResult <string> > SaveVideo(string videoPath) { var tcs = new TaskCompletionSource <OperationResult <string> >(); if (string.IsNullOrEmpty(videoPath) || !File.Exists(videoPath)) { tcs.SetResult(OperationResult <string> .AsFailure("Invalid video file path specified")); return(tcs.Task); } var url = NSUrl.CreateFileUrl(videoPath, false, null); string localId = string.Empty; PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() => { var request = PHAssetChangeRequest.FromVideo(url); localId = request?.PlaceholderForCreatedAsset?.LocalIdentifier; }, (bool success, NSError error) => { if (!success && error != null) { tcs.SetResult(OperationResult <string> .AsFailure(error.LocalizedDescription)); } else { tcs.SetResult(OperationResult <string> .AsSuccess(localId)); } }); return(tcs.Task); }
private Task <OperationResult <LibraryMediaItem> > GetLastSavedMediaItem(MediaItemType itemType) { var tcs = new TaskCompletionSource <OperationResult <LibraryMediaItem> >(); var fetchOptions = new PHFetchOptions(); fetchOptions.SortDescriptors = new NSSortDescriptor[] { new NSSortDescriptor("creationDate", false) }; var fetchResult = PHAsset.FetchAssets(itemType == MediaItemType.Video ? PHAssetMediaType.Video : PHAssetMediaType.Image, fetchOptions); var phAsset = fetchResult?.firstObject as PHAsset; if (phAsset != null) { PHImageManager.DefaultManager.RequestAvAsset(phAsset, null, (asset, audioMix, info) => { var urlAsset = asset as AVUrlAsset; tcs.SetResult(OperationResult <LibraryMediaItem> .AsSuccess(new LibraryMediaItem(phAsset.LocalIdentifier, urlAsset.Url.AbsoluteString))); }); } else { tcs.SetResult(OperationResult <LibraryMediaItem> .AsFailure("Could not retrieve last asset")); } return(tcs.Task); }
public OperationResult OpenExternalApp(string url) { var uri = Android.Net.Uri.Parse(url); var intent = new Intent(Intent.ActionView, uri); Context.StartActivity(intent); return(OperationResult.AsSuccess()); }
private Task <OperationResult> GetMediaItem(string destinationPath, MediaItemType mediaItemType, UIImagePickerControllerSourceType sourceType) { var tcs = new TaskCompletionSource <OperationResult>(); var picker = new ExtendedUIImagePickerController(); picker.PreferredOrientation = UIApplication.SharedApplication.StatusBarOrientation; if (mediaItemType == MediaItemType.Video) { picker.VideoQuality = UIImagePickerControllerQualityType.At1280x720; } picker.SourceType = sourceType; var typeString = mediaItemType == MediaItemType.Video ? "public.movie" : "public.image"; picker.MediaTypes = new string[] { typeString }; picker.Canceled += (object sender, EventArgs e) => { tcs.SetResult(OperationResult.AsCancel()); picker.DismissViewController(true, null); }; picker.FinishedPickingMedia += (object sender, UIImagePickerMediaPickedEventArgs e) => { picker.DismissViewController(true, () => { NSUrl mediaURl = null; if (e.MediaUrl != null) { mediaURl = e.MediaUrl; File.Copy(mediaURl.Path, destinationPath, true); tcs.SetResult(OperationResult.AsSuccess()); } else { var originalImage = e.OriginalImage; var imageData = originalImage.AsJPEG(); NSError err = null; if (imageData.Save(destinationPath, false, out err)) { tcs.SetResult(OperationResult.AsSuccess()); } else { tcs.SetResult(OperationResult.AsFailure(err.LocalizedDescription)); } } }); }; NavigationHelper.GetActiveViewController().PresentViewController(picker, true, null); return(tcs.Task); }
public void Combine_ShouldSucceed_WhenResultConsistsAllSuccess() { var res1 = OperationResult.AsSuccess(); var res2 = OperationResult.AsSuccess(); var res3 = OperationResult.AsSuccess(); var r = OperationResult.Combine(res1, res2, res3); Assert.True(r.IsSuccessful); Assert.False(r.Message.Contains("failed")); }