Facebook api with monotouch - c#

I'm having troubles using the facebook binding from here ( https://github.com/mono/monotouch-bindings/tree/master/facebook ) and the problem is that the authorize ( login ) function doesn't work on the device. On the simulator it's working perfect, but from the device instead of the webbrowser login window it launches the official facebook app ( installed on the phone ).
The same thing happens with the sample provided with the binding.
Any ideeas how can I use the browser to login ( if I unninstall the official facebook app it works ok on the device also ) instead of the facebook app?
The code I use:
class SessionDelegate : FBSessionDelegate
{
AppDelegate container;
NSAction onLogin;
public NSAction OnLogin {
get {
return this.onLogin;
}
set {
onLogin = value;
}
}
public SessionDelegate (AppDelegate container)
{
this.container = container;
}
public override void DidNotLogin (bool cancelled)
{
Console.WriteLine("did not login");
//container.SaveAuthorization ();
if( OnLogin != null ) OnLogin.Invoke();
}
public override void DidLogin ()
{
Console.WriteLine("login !");
container.SaveAuthorization ();
if( OnLogin != null ) OnLogin.Invoke();
}
public override void DidLogout ()
{
Console.WriteLine("logout !");
container.ClearAuthorization();
}
}
And:
var sessionDelegate = new SessionDelegate (this);
facebook = new Facebook (LocalSettings.FacebookAppId, sessionDelegate);
var defaults = NSUserDefaults.StandardUserDefaults;
if (defaults ["FBAccessTokenKey"] != null && defaults ["FBExpirationDateKey"] != null)
{
facebook.AccessToken = defaults ["FBAccessTokenKey"] as NSString;
facebook.ExpirationDate = defaults ["FBExpirationDateKey"] as NSDate;
}
and for login:
facebook.Authorize(new string [] { "email", "publish_stream", "read_friendlists", "user_photos" });

Okay, so I found the answer myself. The problem was in the facebook developer app settings, the iOS Bundle ID didn't was the same with the one in monodevelop identifier :)

This functionality is the developer's intend. First I don't understand why you don't want this and Second this is a open-source library. you can walk through the code and find the piece of code that makes it. Then change it to what you want. I am now searching for this in this library. As long as I got the answer I reply it. But my guess is that they have used UIApplication.SharedApplication.* to open up Facebook app if it is available.
Sincerely yours,
Peyman Mortazavi

FWIW: you'll get the same error if you are in the sandbox and try to logon with a real user.

Related

CustomPresenter errors on migration from 4.4 to 5.7 in MVVMCross

Hello stackoverflowers,
I am working on a project that is built using MVVMCross and Xamarin for iOS and Android. I have found out that the project uses a quite old version of MVVMCross (4.4.0) and I am trying to bring it up to the current one (6.4). I thought it's a good idea to first upgrade to 5.7 and on a later stage, when I have the navigation switched to the new form etc, I will bump up to 6++. I have sucessfully run the android version to 5.7, however, the iOS version uses a customPresenter, that I don't quite know how to transform to the new Presenter introduced in 5.1. I think my custom presenter is based on https://github.com/MvvmCross/MvvmCross-Samples/tree/master/XPlatformMenus/XPlatformMenusTabs.iOS which hasn't been updated in a while.
In my MvxTabPresenter that subclasses MvxIosViewPresenter, the show function is no longer overridable. In addition IMvxModalIosView doesnt seem to exist anymore.
public override void Show(IMvxIosView view)
{
if (view is IMvxModalIosView)
{
if (this._currentModalViewController != null)
{
return;
}
var currentModalViewController = view as MvxViewController;
this._currentModalViewController = currentModalViewController;
currentModalViewController.ModalPresentationStyle = UIModalPresentationStyle.Popover;
CurrentTopViewController.AddChildViewController(currentModalViewController);
currentModalViewController.View.Frame = CurrentTopViewController.View.Bounds.Inset(10, 10);
currentModalViewController.View.Alpha = 0;
CurrentTopViewController.View.Add(currentModalViewController.View);
currentModalViewController.DidMoveToParentViewController(CurrentTopViewController);
UIView.Animate(0.25, () =>
{
currentModalViewController.View.Alpha = 1;
});
//this.PresentModalViewController(currentModalViewController, true);
return;
}
if (view is HomeView)
{
if (this.CurrentTopViewController is MvxTabBarViewController)
{
TabBarPresenter.SelectedIndex = 0;
return;
}
public override void CloseModalViewController()
{
if (this._currentModalViewController != null)
{
this._currentModalViewController.DismissModalViewController(true);
_currentModalViewController.WillMoveToParentViewController(null);
_currentModalViewController.View.RemoveFromSuperview();
_currentModalViewController.RemoveFromParentViewController();
this._currentModalViewController = null;
return;
}
base.CloseModalViewController();
}
}
Also this is no longer overridable from the superclass.
Any suggestions on how to approach this?
Kind regards,
V
As you may see in the MvxIosViewPresenter now the mvx attributes are registered with the action that should be called.
So, firstly you should inherit from MvxIosViewPresenter. Then, for modal you should override ShowModalViewController.
I suggest you to read the docs, the MvxIosViewPresenter and MvxAttributeViewPresenter files on the repo to check out how it works.
HIH

Observe and delete (screenshot), if a screenshot is taken while using my App in Iphone

I am trying to observe if a screenshot is taken while using my App on Iphone. If a screenshot is taken while using my App, I would like that screenshot to be deleted.
I also understand that during deletion, user needs to give permission for deletion.
I used an Observer method successfully to check if a screenshot is taken while using my app.
I am stuck at a point where I need to access that screenshot and delete it, of course with user permission.
```public override void OnActivated(UIApplication application)
{
try
{
// Start observing screenshot notification
if (_screenshotNotification == null)
{
_screenshotNotification = NSNotificationCenter.DefaultCenter.AddObserver(UIApplication.UserDidTakeScreenshotNotification,
(NSNotification n) => {
Console.WriteLine("UserTookScreenshot");
var photosOptions = new PHFetchOptions();
photosOptions.SortDescriptors = new NSSortDescriptor[] { new
NSSortDescriptor("creationDate", false) };
photosOptions.FetchLimit = 1;
var photo = PHAsset.FetchAssets(photosOptions);
Console.WriteLine(photo);
var filePath = photo.Path;
System.IO.File.Delete(filePath);
n.Dispose();
}
);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
}```
I know the above code does not work with deleting the current screenshot taken while using my App. It gives a general idea on what I want to achieve.
How can I delete the screenshot taken while using my APP from Iphone instantly (with user permission)? I would also like to know if it is possible.
Yes it is possible, you obviously have to properly manage the permissions for the image. In order to do this, first you have to add an observer to detect the screenshot as shown here
First: declare an NSObject variable on your AppDelegate. In the example below I added _screenshotNotification.
Second: On the AppDelegate’s OnActivated (app moving to active state), add code to start observing the UIApplication.UserDidTakeScreenshotNotification and then do something once the notification is posted.
Third: On the AppDelegate’s OnResignActivation (app moving to inactive state), add code to remove the observer.
Then you have to actually find the file & delete, so you in the page you are trying to do it, just add the Foundation & Photos using statements and then try this. (I converted the Swift from here but haven't tested it)
var fetchOptions = new PHFetchOptions();
fetchOptions.SortDescriptors[0] = new Foundation.NSSortDescriptor("creationDate", true);
var fetchResult = PHAsset.FetchAssets(PHAssetMediaType.Image, fetchOptions);
if (fetchResult != null)
{
var lastAsset = (fetchResult.LastObject as PHAsset);
var arrayToDelete = new PHAsset[1] { lastAsset };
PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() => { PHAssetChangeRequest.DeleteAssets(arrayToDelete); },
async (bool success, NSError errorMessage) => { }); //Handle Completion Here Appropriately
}
I don't think it is possible.
From iOS 11, when you take a screenshot, the snap minimizes itself in the bottom left corner of the screen. From here, save or delete the screenshot is decided by the user.(as the image below)
You can read more information form this article: how-take-screenshot-iphone-or-ipad-ios-11
Here comes the problem how do you know whether user has save the screenshot or not?
If the user saved, you can delete the screenShot form the photoLibrary.
While if the user dose not save the screenshot, what your deleted is not the screenshot.
Try this:
func didTakeScreenshot() {
self.perform(#selector(deleteAppScreenShot), with: nil, afterDelay: 1, inModes: [])
}
#objc func deleteAppScreenShot() {
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors?[0] = Foundation.NSSortDescriptor(key: "creationDate", ascending: true)
let fetchResult = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: fetchOptions)
guard let lastAsset = fetchResult.lastObject else { return }
PHPhotoLibrary.shared().performChanges {
PHAssetChangeRequest.deleteAssets([lastAsset] as NSFastEnumeration)
} completionHandler: { (success, errorMessage) in
if !success, let errorMessage = errorMessage {
print(errorMessage.localizedDescription)
}
}
}

Is it possible to develop a CarPlay app using Xamarin tools

As the title states, I am trying to build an app for my car. I only see a brief mention of CarPlay in Xamarin docs.
So is it possible to develop a CarPlay app with Xamarin and Visual Studio tools?
P.S. I did some more research and while you could develop apps for CarPlay, Apple only allows navigation and streaming apps as time of writing. So it's a complete non-starter for what I wanted to do.
Yes its possible.
I made a blog post and an example on GitHub.
Here the answer in short:
In our iOS project we init the delegates in the AppDelegate.cs with CarIntegrationBridge.Init();.
The delegates are registered as follow:
public class CarIntegrationBridge : ICarIntegrationBridge
{
public static void Init()
{
PlayableContentDelegate playableContentDelegate = new PlayableContentDelegate();
MPPlayableContentManager.Shared.Delegate = playableContentDelegate;
PlayableContentDataSource playableContentDataSource = new PlayableContentDataSource();
MPPlayableContentManager.Shared.DataSource = playableContentDataSource;
}
}
Now we define our datasource. In my example I added radio stations with name and url. We have to define the menu items count and how a menu item is displayed (name, icon, …):
internal class PlayableContentDataSource : MPPlayableContentDataSource
{
public static List<Station> Stations = new List<Station>
{
new Station{Name = "Rainbow radio", Url = "https://stream.rockantenne.de/rockantenne/stream/mp3"},
new Station{Name = "Unicorn radio", Url = "http://play.rockantenne.de/heavy-metal.m3u"}
};
public override MPContentItem ContentItem(NSIndexPath indexPath)
{
var station = Stations[indexPath.Section];
var item = new MPContentItem(station.Url);
item.Title = station.Name;
item.Playable = true;
item.StreamingContent = true;
var artWork = GetImageFromUrl("station.png");
if (artWork != null)
{
item.Artwork = artWork;
}
return item;
}
public override nint NumberOfChildItems(NSIndexPath indexPath)
{
if (indexPath.GetIndexes().Length == 0)
{
return Stations.Count;
}
throw new NotImplementedException();
}
private MPMediaItemArtwork GetImageFromUrl(string imagePath)
{
MPMediaItemArtwork result = null;
try
{
using (var nsUrl = new NSUrl(imagePath))
{
using (var data = NSData.FromUrl(nsUrl))
{
var image = UIImage.LoadFromData(data);
result = new MPMediaItemArtwork(image);
}
}
}
catch
{
UIImage image = UIImage.FromBundle(imagePath);
if (image != null)
{
result = new MPMediaItemArtwork(image);
}
}
return result;
}
}
Now we have to decide what is todo, if an item is taped.
The simulator have an other behavior than a real device. So I hacked a solution for calling the NowPlayingScene.
internal class PlayableContentDelegate : MPPlayableContentDelegate
{
public override void InitiatePlaybackOfContentItem(
MPPlayableContentManager contentManager, NSIndexPath indexPath, Action<NSError> completionHandler)
{
Execute(contentManager, indexPath);
completionHandler?.Invoke(null);
}
private void Execute(MPPlayableContentManager contentManager, NSIndexPath indexPath)
{
DispatchQueue.MainQueue.DispatchAsync(async () => await ItemSelectedAsync(contentManager, indexPath));
}
private async Task ItemSelectedAsync(MPPlayableContentManager contentManager, NSIndexPath indexPath)
{
// Play
var station = PlayableContentDataSource.Stations[indexPath.Section];
await CrossMediaManager.Current.Play(station.Url);
// Set playing identifier
MPContentItem item = contentManager.DataSource.ContentItem(indexPath);
contentManager.NowPlayingIdentifiers = new[] { item.Identifier };
// Update on simulator
if (DeviceInfo.DeviceType == DeviceType.Virtual)
{
InvokeOnMainThread(() =>
{
UIApplication.SharedApplication.EndReceivingRemoteControlEvents();
UIApplication.SharedApplication.BeginReceivingRemoteControlEvents();
});
}
}
}
To reload the data (e.g. if you change the stations), you have to call this:
public void ReloadStations()
{
MPPlayableContentManager.Shared?.ReloadData();
}
I managed to build an Apple CarPlay app with Xamarin, although I used quite a different approach to what Suplanus did because I didn't create a music app, my approach followed the Apple docs approach more closely.
First make sure your provisioning profile has the correct CarPlay entitlement.
Add the entitlement to Entitlements.plist file.
In your info.plist like suggested in Apple's docs:
<key>UIApplicationSceneManifest</key>
<dict>
<key>UISceneConfigurations</key>
<dict>
<!-- Device Scene -->
<key>UIWindowSceneSessionRoleApplication</key>
<array>
<dict>
<key>UISceneConfigurationName</key>
<string>Default Configuration</string>
<key>UISceneDelegateClassName</key>
<string>DeviceSceneDelegate</string>
</dict>
</array>
<!-- Carplay Scene -->
<key>CPTemplateApplicationSceneSessionRoleApplication</key>
<array>
<dict>
<key>UISceneClassName</key>
<string>CPTemplateApplicationScene</string>
<key>UISceneConfigurationName</key>
<string>YourAppName-Car</string>
<key>UISceneDelegateClassName</key>
<string>YourAppName.CarPlaySceneDelegate</string>
</dict>
</array>
</dict>
</dict>
I then used the solution suggested in this thread to send CarPlay to the correct delegate, with the following changes:
On my CarPlaySceneDelegate class inherit directly from CPTemplateApplicationSceneDelegate.
Implement override methods for DidConnect and DidDisconnect instead.
UIWindowSceneSessionRole.CarTemplateApplication has now been added to the enum, so use that instead of checking in the catch if it’s a CarPlay app in AppDelegate class's GetConfiguration override.
Return default configuration in GetConfiguration override if it's not a CarPlay app.
You'll notice all the classes mentioned in Apple's developer docs are available in the CarPlay library that lives in Xamarin.iOS, so it's not too difficult to translate the swift code to C# to create and display the required templates.
Finally, use this solution to launch your Xamarin.Forms app from the device scene delegate instead of seeing a blank screen on your phone when you open the app.
Hope this helps a bit that you don't have to struggle as much as I did to get it working!
Maybe this https://forums.xamarin.com/discussion/144790/android-auto-ios-car-play answers the question ?
Car Play seems to be a private framework on Apple's side. And there is no relative documentation for XCode.
For Android Auto, go to github, search project Xamarin_Android_Auto_Test

Unable to open App Store from app programmatically

I had been trying to open/navigate App Store from my application when there is a version upgrade.
For that I have written customrender which works perfectly fine for android. But it's not working for iOS. Following is the code written for iOS customrenderer. I attached the screenshot of the code in an attachment.
public class OpenAppStore : UIViewController, ISKStoreProductViewControllerDelegate, IOpenStore
{
public void OpenStore()
{
bool isSimulator = Runtime.Arch == Arch.SIMULATOR;
if (!isSimulator)
{
var storeViewController = new SKStoreProductViewController();
storeViewController.Delegate = this;
var id = SKStoreProductParameterKey.ITunesItemIdentifier;
var productDictionaryKeys = new NSDictionary("SKStoreProductParameterITunesItemIdentifier", 1389696261);
var parameters = new StoreProductParameters(productDictionaryKeys);
storeViewController.LoadProduct(parameters, (bool loaded, NSError error) =>
{
if ((error == null) && loaded)
{
this.PresentViewController(storeViewController, true, () =>
{
Console.WriteLine("SKStoreProductViewController Completed");
});
}
if (error != null)
{
throw new NSErrorException(error);
}
});
}
else
{
var itunesLink = new NSUrl("https://itunes.apple.com/us/genre/ios/id36?mt=8");
UIApplication.SharedApplication.OpenUrl(itunesLink, new NSDictionary() { }, null);
}
}
}
Problem : It doesn't throw any error. PresentViewController is called but it doesn't navigate/open my app in the App Store.
Thank you
Firstly, you don't need a custom renderer for this. You should inject a simple helper class that will open the appropriate app store for each platform you support.
Secondly, the url you are using for the iOS App Store looks to be incorrect. Use something like:
var url = new NSUrl($"https://itunes.apple.com/us/app/apple-store/{myAppId}?mt=8");
The app store URL used above is from the Apple docs. You can then open that url.

How to open settings programmatically in ios

I was searching for the Xamarin implementation of How to open settings programmatically
Vito-ziv answered it for objective C - what is the correct way to do this in C# for iOS in Xamarin Studio?
For current devices this is only possible in ios8 (ios9 not available at time of writing) (It used to be possible before ios5 apparently - see this blog post from Adrian Stevens at Xamarin - shout out to him for the inspiration for this answer)
To do it in ios8, I did it like this:
var settingsString = UIKit.UIApplication.OpenSettingsUrlString;
var url = new NSUrl (settingsString);
UIApplication.SharedApplication.OpenUrl (url);
Where the above code was called from a click event via delegate class in a UIAlertView click.
Since I am supporting ios7 too, to handle ios7 devices I did this, where the HandleLocationAuthorisation method is called when deciding whether to present a view controller - the user on ios8 and above can choose to go to the settings directly, whereas the user on ios7 has to go there manually.
This example below is checking for location services, but with trivial changes could easily be changed to check for other types of settings.
public bool HandleLocationAuthorisation ()
{
if (CLLocationManager.Status == CLAuthorizationStatus.AuthorizedAlways) {
return true;
} else {
UIAlertView uiAlert;
//iOS 8 and above can redirect to settings from within the app
if (UIDevice.CurrentDevice.CheckSystemVersion(8,0)) {
uiAlert = new UIAlertView
("Location Services Required",
"",
null,
"Return To App","Open Settings");
uiAlert.Delegate = new OpenSettingsFromUiAlertViewDelegate();
uiAlert.Message = "Authorisation to use your location is required to use this feature of the app.";
//ios7 and below has to go there manually
} else {
uiAlert = new UIAlertView
("Location Services Required",
"Authorisation to use your location is required to use this feature of the app. To use this feature please go to the settings app and enable location services",
null,
"Ok");
}
uiAlert.Show ();
return false;
}
}
For completeness, here is the code for the event delgate referenced above:
public class OpenSettingsFromUiAlertViewDelegate : UIAlertViewDelegate {
public override void Clicked (UIAlertView alertview, nint buttonIndex)
{
if (buttonIndex == 1) {
var settingsString = UIKit.UIApplication.OpenSettingsUrlString;
var url = new NSUrl (settingsString);
UIApplication.SharedApplication.OpenUrl (url);
}
}
}
Hope this will help you. This is working in iPhone not sure about working on iPad.
var url = new NSUrl("prefs:root=Settings");
UIApplication.SharedApplication.OpenUrl(url);

Categories

Resources