I'm trying to add AdMob banner in my Xamarin iOS project. You can see my code below.
public void AddAdvirtesement()
{
var adView = new BannerView();
adView.Frame = new CGRect(0, View.Bounds.Height - 50, View.Bounds.Width, 50);
adView.BackgroundColor = UIColor.Gray;
adView.AdUnitID = bannerId;
adView.RootViewController = this;
View.AddSubview(adView);
var request = Request.GetDefaultRequest();
string[] testdevices = new string[2];
//testdevices[0] = Request.SimulatorId.ToString();
//testdevices[1] = "b5f64ec8566bf1a5cd1cb853d7106aa7";
request.TestDevices = testdevices;
adView.LoadRequest(request);
}
i get this output above code:
2016-12-11 22:25:42.659 betcluev4[9220:627724] You are
currently using version 7.11.0 of the SDK. Please consider updating
your SDK to the most recent SDK version to get the latest features and
bug fixes. The latest SDK can be downloaded from .......
but I already have the latest SDK of Firebase (7.11.0). Any thoughts?
Check out the plist configurations for FireBase that are needed in your project , and the sample code below
Configurations
Once you have your GoogleService-Info.plist file downloaded in your computer, do the following steps in Xamarin Studio:
Add GoogleService-Info.plist file to your app project.
Set GoogleService-Info.plist build action behaviour to Bundle Resource by Right clicking/Build Action.
Open GoogleService-Info.plist file and change IS_ADS_ENABLED value to Yes.
Add the following line of code somewhere in your app, typically in your AppDelegate's FinishedLaunching method (don't forget to import Firebase.Analytics namespace):
App.Configure ();
Sample Code
using Google.MobileAds;
const string bannerId = "<Get your ID at google.com/ads/admob>";
BannerView adView;
bool viewOnScreen = false;
public void AddBanner ()
{
// Setup your BannerView, review AdSizeCons class for more Ad sizes.
adView = new BannerView (size: AdSizeCons.Banner, origin: new CGPoint (0, 0)) {
AdUnitID = bannerId,
RootViewController = this
};
// Wire AdReceived event to know when the Ad is ready to be displayed
adView.AdReceived += (object sender, EventArgs e) => {
if (!viewOnScreen) {
View.AddSubview (adView);
viewOnScreen = true;
}
};
var request = Request.GetDefaultRequest ();
// Requests test ads on devices you specify. Your test device ID is printed to the console when
// an ad request is made. GADBannerView automatically returns test ads when running on a
// simulator. After you get your device ID, add it here
request.TestDevices = new [] { Request.SimulatorId.ToString () };
// Request an ad
adView.LoadRequest (request);
}
Related
Which is the best/simplest option to add app rating on a Xamarin.Forms application, the default stars form directly connected to the Play Store or App Store?
Edit: I've created an nuget package for this, you can download from Here or check the GitHub repo.
On Android you must open the PlayStore in order to rate the app, on iOS you can do it inside the app, but only from iOS 10 onwards.
You must implement native methods and use it via dependecy service.
Interface
public interface IAppRating
{
void RateApp();
}
Android
public class AppRatiing : IAppRating
{
public void RateApp()
{
var activity = Android.App.Application.Context;
var url = $"market://details?id={(activity as Context)?.PackageName}";
try
{
activity.PackageManager.GetPackageInfo("com.android.vending", PackageInfoFlags.Activities);
Intent intent = new Intent(Intent.ActionView, Uri.Parse(url));
activity.StartActivity(intent);
}
catch (PackageManager.NameNotFoundException ex)
{
// this won't happen. But catching just in case the user has downloaded the app without having Google Play installed.
Console.WriteLine(ex.Message);
}
catch (ActivityNotFoundException)
{
// if Google Play fails to load, open the App link on the browser
var playStoreUrl = "https://play.google.com/store/apps/details?id=com.yourapplicationpackagename"; //Add here the url of your application on the store
var browserIntent = new Intent(Intent.ActionView, Uri.Parse(playStoreUrl));
browserIntent.AddFlags(ActivityFlags.NewTask | ActivityFlags.ResetTaskIfNeeded);
activity.StartActivity(browserIntent);
}
}
}
iOS
public class AppRating : IAppRating
{
public void RateApp()
{
if (UIDevice.CurrentDevice.CheckSystemVersion(10, 3))
SKStoreReviewController.RequestReview();
else
{
var storeUrl = "itms-apps://itunes.apple.com/app/YourAppId";
var url = storeUrl + "?action=write-review";
try
{
UIApplication.SharedApplication.OpenUrl(new NSUrl(url));
}
catch(Exception ex)
{
// Here you could show an alert to the user telling that App Store was unable to launch
Console.WriteLine(ex.Message);
}
}
}
}
On Android (tested in 9.0) I have to add this flag at FabriBertani´s solution:
activity.StartActivity(intent);
The Store Review Nuget plugin has been updated to v3 recently thanks to the new (August 2020) Android native Play Core library so that it displays an In-App Review on both iOS & Android using just one line of code:
await CrossStoreReview.Current.RequestReview(false);
So now, you don't have to worry about opening the url of the app in the external store or a web view, it will be shown directly in the app. You can see more details on this Microsoft Blog
Just remember to add the necessary code in the proguard file mentioned in the README of the Nuget's GitHub repository
I am adding a "Today" extension widget to my iOS app that I made with Xamarin. I am following this walkthrough:
https://developer.xamarin.com/guides/ios/platform_features/introduction_to_extensions/
The widget appears in my Notification section in the simulator, but I can't get any contents to appear in it. It won't even create the UIViewController class that I made and set as the initial controller to start with (I know because it never hits my breakpoint in the constructor). I set it as the principal class with this key as explained in the walkthrough:
Any idea why? I also get this message when I first launch the app after adding the extension:
appname may slow down your phone the developer of this app needs to update it to improve its compatibility
I made a sample project, with Xamarin, and the widget does appear in this project when deployed on the simulator, just not with the contents that I'm trying to add in the CodeViewController class:
https://drive.google.com/file/d/0B8xKHTqtwfKtY0xZN0xaejhlZmM/view?usp=sharing
To save you 2 days I spent on it here is the solution.
Don't run it on simulator. It doesn't work (at least on mine).
Don't try to hit breakpoint in VS. When you testing your extension your app is in background mode. VS will not give you to stop in debugger. To prove run any of your apps, press home and try to set breakpoint in VS. VS will hang till you bring your app to foreground.
Do not use View.Frame in DidLoad. The size of the frame there is the whole screen size, so when you put your label to center you will not see it. Use WillAppear like this
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
if (TodayMessage == null)
{
// Add label to view
TodayMessage = new UILabel(new CGRect(0, 0, View.Frame.Width, View.Frame.Height))
{
TextAlignment = UITextAlignment.Center,
BackgroundColor = UIColor.LightGray,
TextColor = UIColor.Black
};
// Calculate the values
var dayOfYear = DateTime.Now.DayOfYear;
var leapYearExtra = DateTime.IsLeapYear(DateTime.Now.Year) ? 1 : 0;
var daysRemaining = 365 + leapYearExtra - dayOfYear;
// Display the message
if (daysRemaining == 1)
{
TodayMessage.Text = String.Format("Today is day {0}. There is one day remaining in the year.", dayOfYear);
}
else
{
TodayMessage.Text = String.Format("Today is day {0}. There are {1} days remaining in the year.", dayOfYear, daysRemaining);
}
View.AddSubview(TodayMessage);
}
}
So I integrated amazon mobile ads into my unity/ios project. I have it all working to where I hide the ads every time a scene changes. Every time I open a scene, the ad shows. So it's all working fine except when you change scenes really quickly. I don't want ads in the main game as it obstructs the view of the users. Every time you get to the retry scene, if you quickly switch from that scene right before an ad loads, that ad will get stuck on the next scene which makes another ad show on top of it. Every time a scene changes it should be hiding the ad not matter how fast you change scenes. Is there any way to make sure it hides the ad if an ad is shown? I'm using the code below:
void Start() {
mobileAds = AmazonMobileAdsImpl.Instance;
ApplicationKey key = new ApplicationKey();
key.StringValue = iosKey;
mobileAds.SetApplicationKey(key);
ShouldEnable enable = new ShouldEnable();
enable.BooleanValue = true;
mobileAds.EnableTesting(enable);
mobileAds.EnableLogging(enable);
Placement placement = new Placement();
placement.Dock = Dock.BOTTOM;
placement.HorizontalAlign = HorizontalAlign.CENTER;
placement.AdFit = AdFit.FIT_AD_SIZE;
response = mobileAds.CreateFloatingBannerAd(placement);
string adType = response.AdType.ToString();
long identifer = response.Identifier;
newResponse = mobileAds.LoadAndShowFloatingBannerAd(response);
bool loadingStarted = newResponse.BooleanValue;
}
void OnDestroy() {
mobileAds.CloseFloatingBannerAd(response);
response = null;
mobileAds = null;
newResponse = null;
}
When did you download the Unity Plugin? There were some issues in an early version of the plugin that this sounds like (the whole, one ad loading over top of another thing). If you have not updated it recently, try downloading the latest version from Amazon and see if the issue still occurs.
The close ad API
mobileAds.CloseFloatingBannerAd(response);
will only work if the ad is already loaded. You need to register for the ad loaded event. If the scene is destroyed, then you would close the ad when the ad loaded event tiggers.
You can register for AdLoaded event as follows, Documentation
using com.amazon.mas.cpt.ads;
bool sceneDestroyed = false; //tracks if scene is destroyed
//Obtain object used to interact with the plugin
IAmazonMobileAds mobileAds = AmazonMobileAdsImpl.Instance;
// Define event handler
private void EventHandler(Ad args)
{
if (sceneDestroyed)
{
mobileAds.CloseFloatingBannerAd(response);
}
else
{
//Do some other job
}
}
//Register for an event
mobileAds.AddAdLoadedListener(EventHandler);
void OnDestroy()
{
sceneDestroyed = true;
}
I'm having a problem with input in libGDX in the iOS backend. It happens when I have Mopub banner ads displayed. When I put my first finger on the screen, I get a touchDown event (pointer = 0) and when it comes to my second finger, nothing is triggered. BUT for some reason it works when I put my second finger near the banner area (I think it's the banner's frame that I'm hitting). When banner ads aren't displayed, everything works fine. Also everything works fine on Android.
I'd really appreciate the help to tackle this problem here.
Thanks in advance.
iOS 8.3;
roboVM 1.2.0;
gdx 1.6.0;
Here's how I load the Banner:
UIApplication application;
String id;
BANNER_SIZE = MPConstants.MOPUB_BANNER_SIZE;
id = BANNER_ID;
rootViewController = application.getKeyWindow().getRootViewController();
banner = new MPAdView(id, BANNER_SIZE);
double bannerWidth = UIScreen.getMainScreen().getBounds().getWidth();
double bannerHeight = bannerWidth / BANNER_SIZE.getWidth() * BANNER_SIZE.getHeight();
banner.setFrame(new CGRect((UIScreen.getMainScreen().getBounds().getWidth() / 2d) - (BANNER_SIZE.getWidth() * .5d), 0, bannerWidth, bannerHeight));
adViewController = new MPAdViewController(banner);
MPAdViewDelegate bannerDelegate = new MPAdViewDelegateAdapter(){
#Override
public UIViewController getViewController() {
return adViewController;
}
};
banner.setDelegate(bannerDelegate);
adViewController.getView().addSubview(banner);
rootViewController.getView().addSubview(adViewController.getView());
if(!isBannerLoaded) {
banner.loadAd();
isBannerLoaded = true;
}
Here's my didFinishLaunching method:
#Override
public boolean didFinishLaunching(UIApplication application, UIApplicationLaunchOptions launchOptions) {
super.didFinishLaunching(application, launchOptions);
//The 0 doesn't do anything. It was something I was trying out.
adController.loadBanner(application, 0);
rootViewController = application.getKeyWindow().getRootViewController();
application.getKeyWindow().setRootViewController(rootViewController);
application.getKeyWindow().addSubview(rootViewController.getView());
application.getKeyWindow().makeKeyAndVisible();
return false;
}
You should add this line to your adViewController
adViewController.getView().setMultipleTouchEnabled(true);
The following code in Xamarin for iOS was working fine prior to the Xamarin for iOS update to v2.0.50727
This is the code in a custom renderer in a Xamarin Forms app
class WatchVideoRenderer : PageRenderer
{
MPMoviePlayerController moviePlayer;
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
var url = new NSUrl("http://192.168.12.4:8085/MediaUploads/1/211/520140731170618/DPM202.mp4");
moviePlayer = new MPMoviePlayerController();
moviePlayer.ContentUrl = url;
moviePlayer.View.Frame = new CGRect((float)((NativeView.Bounds.Width - 600) / 2), (float)((NativeView.Bounds.Height - 450) / 2), 600, 400);
MPMoviePlayerController.Notifications.ObserveLoadStateDidChange(OnLoadStateChanged);
MPMoviePlayerController.Notifications.ObservePlaybackDidFinish(OnPlaybackComplete);
View.AddSubview(moviePlayer.View);
moviePlayer.PrepareToPlay();
moviePlayer.ShouldAutoplay = true;
moviePlayer.Play();
}
private void OnLoadStateChanged(object sender, NSNotificationEventArgs e)
{
if (moviePlayer.LoadState == MPMovieLoadState.Playable)
{
}
}
private void OnPlaybackComplete(object sender, MPMoviePlayerFinishedEventArgs e)
{
}
}
As i said this was working till day before yesterday, after which I installed 2 updates on Xamarin. iOS & this is now failing. All i see is a black canvas & the video never loads.
No notifications from the MPMoviePlayerController are ever raised.
There is a release of this app scheduled for next week & this last minute bug is causing me headaches. Any help is really appreciated.
I resolved a similar issue by pushing a new image context and that did the trick. I modified the code to include the BeginImageContext() and EndImageContext().
UIGraphics.BeginImageContext(new CGSize(1,1));
var url = new NSUrl("http://192.168.12.4:8085/MediaUploads/1/211/520140731170618/DPM202.mp4");
moviePlayer = new MPMoviePlayerController();
moviePlayer.ContentUrl = url;
moviePlayer.View.Frame = new CGRect((float)((NativeView.Bounds.Width - 600) / 2), (float)((NativeView.Bounds.Height - 450) / 2), 600, 400);
UIGraphics.EndImageContext();
Try switching to AVPlayerViewController instead of MPMoviePlayerController. Throw this code inside your OnElementChanged method.
My renderer was a view renderer and not a page renderer so you might have to tweak it a bit.
if(Control == null)
{
AVPlayerViewController avpvc;
AVPlayer avp;
var url = NSUrl.FromString("SOME URL HERE"); //or NSUrl.FromFile
avp = new AVPlayer(url);
avpvc = new AVPlayerViewController();
avpvc.Player = avp;
avpvc.ShowsPlaybackControls = true;
avp.Play();
this.SetNativeControl(avpvc.View);
}