Titanium/ Appcelerator/ Alloy: Unable to get current location despite success returning true - ios

I am running the following code using the iPhone 4s simulater:
Ti.Geolocation.getCurrentPosition(function(e){
Ti.API.log(JSON.stringify(e));
});
A formatted version of the output of the above gives the following information:
{
"code": 0,
"type":"location",
"error":"The operation couldn’t be completed. (kCLErrorDomain error 0.)",
"source":{},
"success":true
}
There seems to be quite contradictory information. It says success is true yet gives an error message.
Furthermore, according to the Location Results Docs, it says that if success is true, it should return a coords field. Yet the above does not have coords on it.
Please also note both of the following returns true so its not a permission issue:
Ti.Geolocation.locationServicesEnabled;
Ti.Geolocation.hasLocationPermissions(Ti.Geolocation.AUTHORIZATION_ALWAYS);

There are 2 things to take notes of:
locationServicesEnabled property for device
hasLocationPermissions method
First of all, you will need to check for 1st property to make sure that the device location is on.
Then you will check for hasLocationPermissions because this can be true even the device location is not on, which I think is your case.
Sample code for this:
var authType = Ti.Geolocation. AUTHORIZATION_ALWAYS;
if (Ti.Geolocation.locationServicesEnabled) {
if (Ti.Geolocation.hasLocationPermissions(authType)) {
// voila...
} else {
Ti.Geolocation.requestLocationPermissions(authType, function (e) {
if (e.success) {
alert('voila...');
}
});
}
} else {
alert('Please turn on your device's location');
}

Related

undefined is not an object (evaluating '_ExponentImagePicker.default.requestMediaLibraryPermissionsAsync') in expo-image-picker

Error from catch error block Image
Hi, I am using expo-image-picker and I stumbled with this error for a while now.
and this is all the necessary code that I use. I'll give a green checkmark for appreciation.
For more information, I have already handled the permission in info.plist.
// Camera & Image Picker
import * as ImagePicker from 'expo-image-picker';
const openImagePicker = async () => {
try {
// Ask the user for the permission to access the media library
const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync()
if (permissionResult.granted === false) {
alert("You've refused to allow this appp to access your photos!");
return;
}
const result = await ImagePicker.launchImageLibraryAsync();
// Explore the result
console.log(result);
if (result.cancelled === false) {
setPickedImagePath(result.uri);
console.log(result.uri);
}
} catch (error) {
alert('Error Occur: ' + error.message)
closeSheet()
}
}
If you are using SDK 44, a permission request is no longer necessary for launching the image picker so you can remove the related code.
Simply call
const result = await ImagePicker.launchImageLibraryAsync({});
If you really want to ask for permission (which as I said is no longer necessary) the correct method is
ImagePicker.getMediaLibraryPermissionsAsync()
and not
ImagePicker.requestMediaLibraryPermissionsAsync()

SourceUnavailableError when requesting getUserMedia for video from about: page

Requesting mic with audio:true works perfectly fine, however requesting webcam video, or screen video is failing with SourceUnavailbleError. I have added the string of browser to the preference media.getusermedia.screensharing.allowed_domains
Code for requesting webcam video:
var param = {
// audio: true, // if just this it works fine
video: true // {mediaSource: 'screen'} does not work either
};
navigator.mediaDevices.getUserMedia(param).then(function(stream) {
console.log('success');
})
.catch(function(err) {
console.error('err:', err)
});
To reproduce this error, open up browser console, and paste the code above like this:
Error given is:
err: MediaStreamError { name: "SourceUnavailableError", message: "Failed to allocate videosource", constraint: "", stack: "" }
Do you know how I can get around this SourceUnvailableError?
I did a lot of digging here - https://dxr.mozilla.org/mozilla-central/source/browser/modules/webrtcUI.jsm#201 - but no success yet.
Thanks

Appcelerator - Getting geolocation information and turning into a URL

I'm still very new to appcelerator but I'm trying to do a small experiment with geolocation. I have some code similar to below, which returns the long and lat to the console. What I would like to is get the long and lat and append them to a URL, e.g http://www.mywebsite.com/lat/long.
I've tried creating a simple alert to show me the current location in the but all it says is Alert: [object GeolocationModule].
Could somebody point me in the right direction so I can learn some more? Thank you
if (Ti.Geolocation.locationServicesEnabled) {
Titanium.Geolocation.purpose = 'Get Current Location';
Titanium.Geolocation.getCurrentPosition(function(e) {
if (e.error) {
Ti.API.error('Error: ' + e.error);
} else {
Ti.API.info(e.coords);
}
});
} else {
alert('Please enable location services');
}
This is how you need to follow the API documentation:
You can have a look at the LocationResults page: https://docs.appcelerator.com/platform/latest/#!/api/LocationResults which leads you to LocationCoordinates: https://docs.appcelerator.com/platform/latest/#!/api/LocationCoordinates
There you can see, that you can use e.coords.latitude or longitude to get the values. Or have a look at the console output. It should show you a JSON output with the key-value pairs.
Once you have the values you can create a HTTP request (demo: https://docs.appcelerator.com/platform/latest/#!/guide/HTTPClient_and_the_Request_Lifecycle) and open your page:
var url = "https://www.appcelerator.com/"+e.coords.longitude+"/"+e.coords.latitude;
var xhr = Ti.Network.createHTTPClient({
onload: function(e) {
// this function is called when data is returned from the server and available for use
// this.responseText holds the raw text return of the message (used for text/JSON)
// this.responseXML holds any returned XML (including SOAP)
// this.responseData holds any returned binary data
Ti.API.debug(this.responseText);
alert('success');
},
onerror: function(e) {
// this function is called when an error occurs, including a timeout
Ti.API.debug(e.error);
alert('error');
},
timeout:5000 /* in milliseconds */
});
xhr.open("GET", url);
xhr.send(); // request is actually sent with this statement
or if you plan to use more request have a look at RESTe (https://github.com/jasonkneen/RESTe) which is an awesome library that makes it easy to create API requests

Potential causes of Ionic function not working in Ionic View, but working on web

I am building a food delivery app using Ionic. And I am having problems getting the app to work on mobile for the address creation step. After creating an account the user must create a delivery address, at which point the app figures out what delivery location to use.
Address creation works in Chrome (ionic serve) and in iOS simulator (ionic run ios -l -c -s).
However, once I've uploaded the app to my Ionic View iOS app for testing, it gets stuck at the Address creation step.
But at the address creation step, the Ionic loading wheel starts but it doesn't go away and there is no state transition to the menu.
Here is the implementation in the controller.
Address.create($scope.newAddress, $scope.user)
.then(function(response) { // never gets a response back in Ionic View
console.log("address created");
user.save(null,
{ success: function(user) {
// success callback
}, error: function(error) {
// throw error
}
});
}, function(error) {
// throw error
});
The Address.create() method I have implemented is fairly lengthy:
...
.factory('Address', ['$http', '$q', 'PARSE_HEADERS'
function ($http, $q, PARSE_HEADERS) {
return {
create: function(data, userID) {
var deferred = $q.defer();
var zipArray = ['1111','22222','33333'];
var inZone = false;
var restaurantCoords = {
latitude: 11.11111, longitude: 22.22222
};
for (var i=0, bLen=zipBrooklyn.length; i<bLen; i++) {
if(data.zipCode==zipArray[i]) {
inZone = true;
}
}
if (inZone == true ) { // valid zip
function onSuccess(coords) {
var limit = 3041.66;
var meters = getDistance(coords, restaurantCoords);
if (meters < limit) {
$http.post('https://api.parse.com/1/classes/Address', data, {
headers: PARSE_HEADERS
})
.success(function(addressData) {
deferred.resolve(addressData);
})
.error(function(error, addressData) {
deferred.reject(error);
});
}
function onError() {
deferred.reject("Unable to Geocode the coordinates");
}
// GET COORDS
navigator.geocoder.geocodeString(onSuccess, onError, data.address1 + ',' + data.zipCode);
}
}
return deferred.promise;
}]);
I've stripped out all of the code that I believe was working.
So a valid answer for this question could take multiple forms:
I'd accept an answer giving a decent way to debug apps IN Ionic View.
Or, if someone could provide an answer as to why it might be working in the browser and in iOS Simulator, but not iOS itself, that would be appreciated even more.
Ionic view doesn't support all the plugins yet. please take a look at this link for the list of supported plugins.
Device is always better (First Option). If you have a ios device and apple developer account. You can create and configure the required certificate with the device id and run the app using 'ionic run ios'. Second option is iOS simulator. You can use the simulator for your whole app, though few tasks would need a device.
Even if you use the simulator for the whole development, it is always advisable to test in the device before launcing the app.

Breeze.js How to display Validation Error Message

during Save changes, there are instance when validation is failing, but how do i get back and display the actual Error Message. The saveFailed function is executed, but i want more details information, about what validations failed and those individual error emssages
function saveChanges() {
if (manager.hasChanges()) {
manager.saveChanges()
.then(saveSucceeded)
.fail(saveFailed);
} else {
alert("Nothing to save");
};
};
function saveSucceeded() {
alert("changes saved successfully");
};
function saveFailed(error) {
alert("Error while saving changes" + error.message);
};
Have a look at the TODO sample that is provided with the breeze download.
The dataservice.js clearly shows you how to catch and display validation errors.
The 'error' object returned by the fail handler, should contain additional details, depending on the error. The following properties should always be there
error.message - the error message
error.status - http error code - usually a 400 or 500 code
error.detail - any details relevant to the error
error.XHR - the raw XML HttpResponse object
error.responseText
For validation errors, right now they appear in the error.message, but we are looking at breaking them out in a cleaner fashion, possibly into another property. But for now they will appear in the error.message.

Resources