bannerview.ad unit is obsolete: use adunitid property instead - xamarin

I'm trying to archive my iOS app and problem shows to me because of Google Mobile Ads .
bannerview.adunit is obsolete: use adunitid property instead
I'm trying to find solution to it
private BannerView CreateBannerView()
{
if (_bannerView != null)
return _bannerView;
var origin = new CGPoint(0, UIScreen.MainScreen.Bounds.Size.Height - AdSizeCons.Banner.Size.Height);
_bannerView = new BannerView(AdSizeCons.SmartBannerPortrait, origin)
{
AdUnitID = Element.AdUnitId,
RootViewController = GetVisibleViewController()
};
_bannerView.LoadRequest(GetRequest());
return _bannerView;
}
private Request GetRequest()
{
var request = Request.GetDefaultRequest();

Related

Broadcast Extension with ReplayKit Xamarin iOS not displaying device screen

I created a Xamarin forms project and added Broadcast Upload Extension and Extension UI and reference them into IOS Project also I followed the instructions in the doc here
https://learn.microsoft.com/en-us/xamarin/ios/platform/extensions#container-app-project-requirements
I uses agora for screen sharing but the result is the device share the camera instead of it's screen
I followed this sample
https://github.com/DreamTeamMobile/Xamarin.Agora.Samples/tree/master/ScreenSharing
and added a Dependency service Interface to invoke it from Xamarin forms all is working expect device share it's camera not it's screen
public class AgoraServiceImplementation : IAgoraService
{
private void JoiningCompleted(Foundation.NSString arg1, nuint arg2, nint arg3)
{
_myId = arg2;
_agoraEngine.SetEnableSpeakerphone(true);
JoinChannelSuccess((uint)_myId);
var bundle = NSBundle.MainBundle.GetUrlForResource("ScreenSharingIOSExtension", "appex", "PlugIns");
var frame = new CGRect(100, 100, 60, 60);
var broadcastPicker = new RPSystemBroadcastPickerView(frame);
var bundle2 = new NSBundle(bundle);
broadcastPicker.PreferredExtension = bundle2.BundleIdentifier;
var vc = Platform.GetCurrentUIViewController();
vc.Add(broadcastPicker);
}
public void StartShareScreen(string sessionId, string agoraAPI, string token, VideoAgoraProfile profile = VideoAgoraProfile.Portrait360P, bool swapWidthAndHeight = false, bool webSdkInteroperability = false)
{
_agoraDelegate = new AgoraRtcDelegate(this);
_agoraEngine = AgoraRtcEngineKit.SharedEngineWithAppIdAndDelegate(agoraAPI, _agoraDelegate);
_agoraEngine.EnableWebSdkInteroperability(webSdkInteroperability);
_agoraEngine.SetChannelProfile(ChannelProfile.LiveBroadcasting);
_agoraEngine.SetClientRole(ClientRole.Broadcaster);
//
_agoraEngine.EnableVideo();
if (!string.IsNullOrEmpty(AgoraSettings.Current.EncryptionPhrase))
{
_agoraEngine.SetEncryptionMode(AgoraSettings.Current.EncryptionType.GetModeString());
_agoraEngine.SetEncryptionSecret(helper.AgoraSettings.Current.EncryptionPhrase);
}
_agoraEngine.StartPreview();
Join();
}
private async void Join()
{
var token = await AgoraTokenService.GetRtcToken(helper.AgoraSettings.Current.RoomName);
if (string.IsNullOrEmpty(token))
{
//smth went wrong
}
else
{
_agoraEngine.JoinChannelByToken(token, AgoraSettings.Current.RoomName, null, 0, JoiningCompleted);
}
}
}
any help ?

SetSound - This API is now obsolete. What to use?

SetSound - This API is now obsolete. What to use?
Can i use .SetDefaults (Resource.Drawable.MYSOUNDMP3) in
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.SetContentTitle ("Sample Notification")
.SetContentText ("Hello World! This is my first notification!")
.SetDefaults (NotificationDefaults.Sound)
.SetSmallIcon (Resource.Drawable.ic_notification);
I did like this, everything works.
i create channel
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
// Notification channels are new in API 26 (and not a part of the
// support library). There is no need to create a notification
// channel on older versions of Android.
return;
}
string name = "MyName";
var description = "Notice";
var channel = new NotificationChannel(CHANNEL_ID, name, NotificationImportance.High)
{
Description = description
};
var soundUri = Android.Net.Uri.Parse($"{ContentResolver.SchemeAndroidResource}://{Application.Context.PackageName}/{Resource.Drawable.mysound}");
var audioAttributes = new AudioAttributes.Builder()
.SetContentType(AudioContentType.Sonification)
.SetUsage(AudioUsageKind.Notification)
.Build();
channel.SetSound(soundUri, audioAttributes);
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.CreateNotificationChannel(channel);
i create notification
var builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.SetContentTitle(SetContentTitle)
.SetContentText(SetContentText)
.SetChannelId(CHANNEL_ID)
.SetSmallIcon(Resource.Drawable.icon);
// Finally, publish the notification:
var notificationManager = NotificationManagerCompat.From(this);
// Publish the notification:
int notificationId = 1;
notificationManager.Notify(notificationId, builder.Build());
changed the AudioUsageKind.Alarm to AudioUsageKind.Notification
You can use NotificationChannel instead of NotificationCompat.Builder
NotificationChannel mChannel;
if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
{
mChannel = new NotificationChannel(CHANNEL_ID, Utils.CHANNEL_NAME, Android.App.NotificationImportance.High);
string description = getString(R.string.channel_description);
mChannel.LightColor(Color.GRAY);
mChannel.EnableLights(true);
mChannel.Description=description ;
var audioAttributes = new AudioAttributes.Builder()
.SetContentType(AudioContentType.Sonification)
.SetUsage(AudioUsageKind.Alarm)
.Build();
var alarmUri = Android.Net.Uri.Parse("MyApp.Android/Resources/raw/alarm.mp3");
mChannel.SetSound(soundUri, audioAttributes);
if (mNotificationManager != null)
{
mNotificationManager.createNotificationChannel(mChannel);
}
}
You can refer this for more information
https://forums.xamarin.com/discussion/137045/xamarin-android-use-setsound-for-notification-channel-to-play-custom-sound-on-notification
SetSound is deprecated on the Android side starting from API level 26. You can read more about it in official Android API documentation
As documentation suggests you can use NotificationChannel's SetSound instead.
You can find a sample how to use NotificationChannels in Xamarin here
SetSound was deprecated on Android from API level 26
SetDefaults should be replaced with the use of the following
NotificationChannel.EnableVibration(boolean)
NotificationChannel.EnableLights(boolean)
NotificationChannel.SetSound(Uri, AudioAttributes)
setSound should be replaced with use of
NotificationChannel.SetSound(Uri, AudioAttributes)
Check the official documents by Android for more information:
https://developer.android.com/reference/android/app/Notification.Builder.html#setDefaults(int)
https://developer.android.com/reference/android/app/Notification.Builder#setSound(android.net.Uri)

Download Photo not saved on local folder Xamarin Forms iOS

Saved image not showing on galary iOS(working fine on Android but not iOS)
Here is my code for saving image to device
public void SavePicture(string name, byte[] data, string location = "Downloads")
{
var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
documentsPath = Path.Combine(documentsPath, location);
Directory.CreateDirectory(documentsPath);
string filePath = Path.Combine(documentsPath, name);
File.WriteAllBytes(filePath, data); // writes to local storage
}
Also allow for photo permission on info.plist
Privacy - Photo Library Usage Description
after execute this code I cant find the saved photo on iOS device
How to solve this?
Well in iOS to show an image into the gallery you have to write additional code as just using File.WriteAllBytes won't call the native UIImageWriteToSavedPhotosAlbum API to show it in the album.
To do that you will have to call this API as follows:
Make a dependency service:
public interface ISavePhotosToAlbum
{
void SavePhotosWithFilePath(String Path);
}
Now Add a native class and do the following:
[assembly: Dependency(typeof(SaveToAlbum))]
namespace SavePhotosDemo.iOS
{
public class SaveToAlbum : ISavePhotosToAlbum
{
public void SavePhotosWithFilePath(String Path)
{
using (var url = new NSUrl (Path))
using (var data = NSData.FromUrl (url))
var image = UIImage.LoadFromData (data);
image.SaveToPhotosAlbum((img, error) =>
{
if (error == null)
{//Success }
else
{//Failure}
});
}
}
}
Then use this Dependency Service as follows:
DependencyService.Get<ISavePhotosToAlbum>().SavePhotosWithStream(imageUrl);
Also, see to it that you add this dependency service call only for ios by adding it in an OnPlatform if statement.
UPDATE
Use the following code to Add a Custom Photo Album in Photos library:
void AddAssetToAlbum(UIImage image, PHAssetCollection album, string imageName)
{
try
{
PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() =>
{
// Create asset request
var creationRequest = PHAssetCreationRequest.CreationRequestForAsset();
var options = new PHAssetResourceCreationOptions
{
OriginalFilename = imageName
};
creationRequest.AddResource(PHAssetResourceType.Photo, image.AsJPEG(), options);
// Change asset request (change album by adding photo to it)
var addAssetRequest = PHAssetCollectionChangeRequest.ChangeRequest(album);
addAssetRequest.AddAssets(new PHObject[] { creationRequest.PlaceholderForCreatedAsset });
}, (success, error) =>
{
if (!success)
Console.WriteLine("Error adding asset to album");
});
}
catch (Exception ex)
{
string h = ex.Message;
}
}
See to it that you request authorization using the PHPhotoLibrary.RequestAuthorization method as we need to request access to be able to use the Photos library. Also, As of iOS 10 and above we also need to add an entry for access in the target .plist file for "Privacy - Photo Library Usage Description":
<key>NSPhotoLibraryUsageDescription</key>
<string>Access to photos is needed to provide app features</string>
Update
At the end, adding the following started showing the documents in the files app:
<key>UIFileSharingEnabled</key> <true/> <key>LSSupportsOpeningDocumentsInPlace</key> <true/>

create local notification in xamarin ios with http request

i have xamarin forms app that support notification, i have done it in android with broadcast receiver now i have to do notification in ios ! , my service is depending on API REST so i want every 60 second ios app run HTTP request and get data then show it as notification, i searched for many days but i can't reach to my approach ?
if this is impossible can i use nuget or something like that in ios project only "in xamarin forms solution " or not ?
content = new UNMutableNotificationContent();
content.Title = "Notification Title";
content.Subtitle = "Notification Subtitle";
content.Body = "This is the message body of the notification.";
content.Badge = 1;
content.CategoryIdentifier = "message";
var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(60, true);
var requestID = "sampleRequest";
var request = UNNotificationRequest.FromIdentifier(requestID, content, trigger);
UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
{
if (err != null)
{
// Do something with error...
}
});
Here is my code for generating a local notification on iOS
var alertsAllowed = false;
UNUserNotificationCenter.Current.GetNotificationSettings((settings) =>
{
alertsAllowed = (settings.AlertSetting == UNNotificationSetting.Enabled);
});
if (alertsAllowed)
{
var content = new UNMutableNotificationContent();
content.Title = "Incident Recorder";
content.Subtitle = "Not Synchronised";
content.Body = "There are one or more new incidents that have not been synchronised to the server.";
var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(5, false);
var requestID = "sampleRequest";
var request = UNNotificationRequest.FromIdentifier(requestID, content, trigger);
UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
{
if (err != null)
{
Console.WriteLine(err.LocalizedFailureReason);
}
});
}
The first parameter in CreateTrigger is how long before the notification is generated. I notice you have 60 in yours. Also bear in mind a notification will not appear if your app is foregrounded.

Sharing targeted xamarin forms

I use the following command to share a link, but with this command opens a box with apps for me to share. I want when I share it already go straight to facebook, without going through this box
void OnTapped4(object sender, EventArgs args)
{
CrossShare.Current.ShareLink(link, "teste", titulo);
}
Need to do direct shares to facebook, whatsapp, twitter and email
I have this command plus it works only on xamarin android, in xamarin forms it would no work
Intent sendIntent = new Intent();
sendIntent.SetAction(Intent.ActionSend);
sendIntent.PutExtra(Intent.ExtraText,"titulo");
sendIntent.SetType("text/plain");
sendIntent.SetPackage("com.facebook.orca");
StartActivity(sendIntent);
I found the following example where I did on android and it worked, now I want to do this in IOS how can I get it to go to whatsapp
Android
public class ShareService : IShareService
{
public void SharePageLink(string url)
{
var context = Forms.Context;
Activity activity = context as Activity;
Intent share = new Intent(Intent.ActionSend);
share.SetType("text/plain");
share.AddFlags(ActivityFlags.ClearWhenTaskReset);
share.PutExtra(Intent.ExtraSubject, "Brusselslife");
share.SetPackage("com.whatsapp");
share.PutExtra(Intent.ExtraText, url);
activity.StartActivity(Intent.CreateChooser(share, "Share link!"));
}
}
In IOS where to put this 'com.whatsapp'
public class ShareService : IShareService
{
public void SharePageLink(string url)
{
var window = UIApplication.SharedApplication.KeyWindow;
var rootViewController = window.RootViewController;
//SetPackage
var activityViewController = new UIActivityViewController(new NSString[] { new NSString(url) }, null);
activityViewController.ExcludedActivityTypes = new NSString[] {
UIActivityType.AirDrop,
UIActivityType.Print,
UIActivityType.Message,
UIActivityType.AssignToContact,
UIActivityType.SaveToCameraRoll,
UIActivityType.AddToReadingList,
UIActivityType.PostToFlickr,
UIActivityType.PostToVimeo,
UIActivityType.PostToTencentWeibo,
UIActivityType.PostToWeibo
};
rootViewController.PresentViewController(activityViewController, true, null);
}
}

Resources