iOS equivalent of accessing Android asset files - xamarin

I have a Xamarin Android application in which I've bundled up some files as assets and I can access them like this: Android.App.Application.Context.Assets.Open(fileName)).
How would I go about doing this in an iOS application?

The NSBundle class is the closest equivalent with using a BundleResource build action:
Example:
var path = NSBundle.MainBundle.BundlePath;
var filePath = Path.Combine(path, "someDataFile.xml");
var someFileContents = File.ReadAllBytes(filePath);
There are also FromBundle overloads on some classes:
var image = UIImage.FromBundle("myimage.png");

Related

Problem with building paths iOS v MacOs in Xamarin Forms app

I have this code:
var myDocuments = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "..", "Shared");
_rootPath = Path.Combine(myDocuments, "VisitsRota.MacOS");
_stylesPath = Path.Combine(_rootPath, "Styles");
_vrrDataFile = Path.Combine(_rootPath, "VisitsRotaData.xml");
// Read in the required data
vrrData = DeserializeFromXml<VisitsRotaData>(_vrrDataFile);
// Build list of month names. Should this property also have a private counterpart?
ListMonths = DateTimeFormatInfo.CurrentInfo.MonthNames.TakeWhile(m => m != String.Empty).ToList();
// Select the current month in the list
ListMonthsSelectedItem = DateTime.Now.ToString("MMMM");
string[] stylesArray = Directory.GetFiles(_stylesPath, "ElderlyInfirm-Schedule-*.xsl")
.Select(file => Path.GetFileName(file)).ToArray<string>();
On the Mac it runs as expect. But on the iOS simulator (which I am new to using) it raises an exception:
System.IO.DirectoryNotFoundException: Could not find a part of the
path
'/Users/xxxxxxx/Library/Developer/CoreSimulator/Devices/B812608B-8131-4386-B189-C646684A8965/data/Containers/Data/Application/EF23B73D-8D38-4F41-995E-FCAE13AE3035/Shared/VisitsRota.MacOS/Styles'.
How should I be able to replicate testing on my iOS build? if I use literal paths instead of Path.Combine etc. I do not have a problem.
I was able to resolve this. My related question / answer about resources helped.
In the comments to this question I was asked:
How are these files being deployed with your app?
That was the key!
I added a constructor to the AppDelegate class:
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
public AppDelegate()
{
InstallApplicationFiles();
}
The linked Q & A has more info. By getting the app to copy the default files from the resources the issue of paths with the iOS simulator is resolved.

How to get app name programatically in native script

I'm trying to save some files on my local File storage So, I'm doing Something like below
var folder_name = "abcde/" + viewModel.dir_path;
const documents = fileSystemModule.knownFolders.documents();
documents._path = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
const folder = documents.getFolder(folder_name);
var file = fileSystemModule.path.join(folder._path, this.pdf_url.split("/").pop());
var url = this.pdf_url;
httpModule.getFile(url, file).then(function(result) {
console.log(result);
Toast.makeText(`${result._name} is succesfully downloaded in ${folder_name}`).show();
}, function(e) {
console.log(e);
});
the only problem is the hardcoded value abcde/ I want it to be app name. whatever the app name is it should take that name.
I don't find any ways to read app name programatically. I need this to Android I'm not interested in IOS.
may be this is one could be the answer. but still this is not a proper way
const documents = fileSystemModule.knownFolders.currentApp();
console.log(documents); --> "/data/data/org.nativescript.app_name/files/app"
var str = documents;
var arr = str.split("/")[3];
console.log(arr.split(".")[2]); ---> app_name
In Android, you can set the app name for the application in strings.xml, for example:
<string name="app_name">"App_Name"</string>
Then whenever you want to reuse the app name, you can use the getString method with its name in the application.

Xamarin Android Background Notification Custom Sound

is it possible to use custom sounds in xamarin android for background notification? I didnt find any examples.
Yep! Here's an example:
var pathToPushSound = $"android.resource://com.your.package/raw/{soundName}";
var soundUri = Android.Net.Uri.Parse(pathToPushSound);
var builder = new NotificationCompat.Builder(_context)
.SetContentTitle("TITLE")
.SetContentText("TEXT")
.SetPriority(1)
.SetSmallIcon(Resource.Drawable.TransparentLogo)
.SetOngoing(true)
.SetSound(soundUri);
builder.Build();
The URI is the path to the resource where your sound file lives, then you set that URI in your NotificationBuilder using the SetSound method.

Get network operator name in Appcelerator Titanium

I am looking to get the name of the operator for the user's Android device.
E.g. "Verizon" or "Vodafone", I think I have found the Android equivalent documented here called getSimOperatorName() from http://developer.android.com/reference/android/telephony/TelephonyManager.html#getNetworkOperatorName()
I am scanning over the documentation for Appcelerator Titanium, but can't seem to find a way of doing this in the docs (http://docs.appcelerator.com/platform/latest/#!/api/Titanium.Network).
Is this possible in Appcelerator Titanium?
You can use tinetworkinfo Module
Ex:-
var netInfo = require('com.clever_apps.tinetworkinfo');
var win = Ti.UI.createWindow({exitOnClose: true});
var testLabel = Ti.UI.createLabel({
height:"80%",
width:"90%",
top:0
});
var refreshButton = Ti.UI.createButton({
title:"Refresh Data",
height:"15%",
bottom:"5%"
});
refreshButton.addEventListener("click", getTelephonyData);
win.add(testLabel);
win.add(refreshButton);
getTelephonyData();
win.open();
function getTelephonyData(){
var imei = netInfo.getIMEI();
var cellid = netInfo.getCellID();
var lac = netInfo.getLac();
var mnc = netInfo.getMNC();
var mmc = netInfo.getMMC();
var outString = "IMEI: "+imei+"\nCell ID: "+cellid+"\nLAC: "+lac+"\nMNC: "+mnc+"\nMMC: "+mmc;
testLabel.text = outString;
}
Currently there is no API that will return you that information. For that, you need to create your own Android module.
I could not get tinetworkinfo Module working. However, a module named TelephonyManager worked fine.
I ran this in the terminal for the project:
gittio install com.goyya.telephonymanager
Then this code to get the network operator name:
var telephonymanager = require("com.goyya.telephonymanager");
Ti.API.log('networkOperatorName: ' + telephonymanager.networkOperatorName);

Detecting the Location your cocoa swift application is running from

I'm trying but unable to find out if there is a way using swift to detect the path and name of the .app file that is running
ie if my app is selfupdater.app and its stored in ~username/applications
how can i get this information when selfupdater.app is launched as a string variable in swift
This is called your main bundle folder.
Swift 3 or later
extension URL {
var parentDirectory: URL? {
return (try? resourceValues(forKeys: [.parentDirectoryURLKey]))?.parentDirectory
}
}
let bundleURL = Bundle.main.bundleURL
if let path = bundleURL.parentDirectory?.path {
print(path)
}

Resources