Showing posts with label cordova. Show all posts
Showing posts with label cordova. Show all posts

Thursday, December 13, 2018

Search keywords in HTML content and highlight


Declare below variables in class
highlightClass = "highlightText";
highlightRe: any;
spaceRe = /\s+/;
spaceRe2 = /\s+$/;
before: any = "";
after: any = "";

Thursday, November 22, 2018

Call a function of Controller "One" inside Controller "Two" - IONIC1

app.controller('One', ['$scope', '$rootScope'
    function($scope) {
        $rootScope.$on("CallParentMethod", function(){
           $scope.parentmethod();
        });

        $scope.parentmethod = function() {
            // task
        }
    }
]);
app.controller('two', ['$scope', '$rootScope'
    function($scope) {
        $scope.childmethod = function() {
            $rootScope.$emit("CallParentMethod", {});
        }
    }
]);

While $rootScope.$emit is called, you can send any data as second parameter.

Solution for IONIC2+  will be up soon.

Whatsapp message from hybrid app


There are two different ways to open whatsapp form hybrid application.

<a target="_blank" href="whatsapp://send?text=hello">open whatsapp</a>



<a target="_blank" href="whatsapp://send?text=my message&phone=+XXXXXXXXXXXX&abid=+XXXXXXXXXXXX">Whatsapp me please</a>


Monday, July 24, 2017

Log execution time of function/Ajax Call



Initialization of the variable to store all logs in controller

$rootScope.timeSlots = {};



//Function to create object with eventname , start time, end time using ID
$scope.logEvent = function(Eventid, EventName, isEnd){
    if(isEnd == false){
         $rootScope.timeSlots[Eventid] = {
            "name": EventName,
            "startDate":new Date().getTime()
         };
    } else {
        $rootScope.timeSlots[Eventid]["endDate"] = new Date().getTime();
    }
};
Log starting time 
$scope.logEvent("function1","Function1 start Time", false);

Tuesday, June 20, 2017

Angular/Ionic not updating an image src when ng-src is empty

The Angular ngSrc directive serves to properly set an image src via Angular. As anything in Angular, it updates the image as soon as the contained Angular expression changes. However, when the ng-src attribute is empty, Angular will not empty the src attribute. To overcome this, use the trick below.
<img ng-src="{{ element.image || '//:0' }}" />

Background

The ngSrc directive explicitly returns when the attribute value is false. As a workaround, set a "blank" image src when the image is empty. As somebody on Stackoverflow writes, //:0 serves this purpose: It adopts the current protocol, omits the hostname and sets the port to zero, which is invalid and should be killed by the network layer.
As a result, Angular should now correctly empty the src attribute when ng-src empties.


Change timeout for connection request in iOS

Code to change ajax request timeout for ios and also for hybrid(Cordova) apps.

Find NSURLRequest in your native code. Change the timeoutInterval value.

  NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:serverURL] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0];



👍

Tuesday, September 6, 2016

IONIC - data binding on header title not working

By using the new ion-nav-title directive in Ionic beta 14, the binding seems to work correctly.
Rather than
<ion-view title="{{content.title}}">

Do this
<ion-view> <ion-nav-title>{{content.title}}</ion-nav-title>

Works a treat.

Monday, August 8, 2016

Self Signed SSL Certificates in PhoneGap

Code to allow self signed certs on PhoneGap 

Android:

  • If you are doing development: android:debuggable="true" in the manifest, you should allow the browser to request data from servers with a self-signed or bad SSL cert 
  • If you are releasing an application, you should remove the android:debuggable="true" (Android Market won't let you release with this on anyway) and you will NOT be able to send data to a server with a bad SSL cert 
  • If you don't have this flag set, the default will be what the default is now, which is that you won't be able to send data to servers with a self-signed cert 

iOS: 

Just Add below code at the end of you AppDelegate.m file
@implementation NSURLRequest(DataController)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString *)host
{
    return YES; 
}
@end

Thursday, June 9, 2016

Error: Database location or iosDatabaseLocation value is now mandatory in openDatabase call

if you are using Cordova sqlite plugin you may have this issue while open local DB file.

 _sqlLiteDB = $cordovaSQLite.openDB({ name: "testDB.db", iosDatabaseLocation:'default'}); 
// Works on android but not in iOS

                   

Error: Database location or iosDatabaseLocation value is now mandatory in openDatabase call



Use below to open DB:
window.sqlitePlugin.openDatabase({ name: "testDB.db", location: 2, createFromLocation: 1});


Solution:

if(isAndroid){
                    // Works on android but not in iOS
                    _sqlLiteDB = $cordovaSQLite.openDB({ name: "testDB.db", iosDatabaseLocation:'default'}); 
} else{
                    // Works on iOS 
                    _sqlLiteDB = window.sqlitePlugin.openDatabase({ name: "testDB.db", location: 2, createFromLocation: 1}); 
 }



Friday, June 3, 2016

Warning: sqlite3.c Ambiguous expansion of macro - Xcode - iOS

Plugin: cordova-sqlite-storage

Version: 1.4.1

Warning: sqlite3.c Ambiguous expansion of macro - Xcode - iOS

This issue also helps on native app code. 


Issue Solution:

Open Xcode project Build settings


add “-Wno-ambiguous-macro” into  “Other C flags” 



Wednesday, June 1, 2016

error JSON.stringify()ing argument: RangeError: Invalid Date

There is minor bug in contact plugin in cordova ionic. contact list is loaded with error due to the birthdate field in contact card. Its bad practice to keep minor error in execution of code, It may effect to different OS versions.

error JSON.stringify()ing argument: RangeError: Invalid Date


Cordova Plugin: cordova-plugin-contacts
Verison: 2.1.0 "Contacts"


Open convertUtils.js file  

File Path: plugins/cordova-plugin-contacts/www/convertUtils.js



Find function "toCordovaFormat" and remove below try-catch code.


 try {
         contact.birthday = new Date(parseFloat(value));
} catch (exception){
          console.log("Cordova Contact toCordovaFormat error: exception creating date.");
}

add below code instead of try-catch

if (value !== null) {
        try {
                contact.birthday = new Date(parseFloat(value));
               
                //we might get 'Invalid Date' which does not throw an error
                //and is an instance of Date.
                if (isNaN(contact.birthday.getTime())) {
                       contact.birthday = null;
               }
               
        } catch (exception){
                console.log("Cordova Contact toCordovaFormat error: exception creating date.");
        }
}

Check below screenshot for better understand.




iOS contact card does not have value for "displayName". "displayName" is used for the android devices. So For iOS device, use "name.formatted" instead of "displayName".

Cheers.... Keep Coding... :)








Wednesday, May 25, 2016

Easily Track Javascript File and line number which has error

When all else fails, the issue may be caused by errors in your JavaScript application. A helpful way to determine this is to use the window.onerror function to track down your errors.

Easily Track Javascript File and line number which has error


window.onerror = function (err, fileName, lineNumber) {
   // alert or console.log a message
   alert(fileName, 'Line:', lineNumber, 'Error:', e.message);
};

Parameter info: 
// err: error message
// fileName: which file error occurs in
// lineNumber: what line error occurs on

Tuesday, January 21, 2014

Phoengap Push Notifications for Android and iOS

DESCRIPTION

This plugin is for use with Cordova, and allows your application to receive push notifications on both Android and iOS devices. The Android implementation uses Google's GCM (Google Cloud Messaging) service, whereas the iOS version is based on Apple APNS Notifications
Important - Push notifications are intended for real devices. The registration process will fail on the iOS simulator. Notifications can be made to work on the Android Emulator. However, doing so requires installation of some helper libraries, as outlined here, under the section titled "Installing helper libraries and setting up the Emulator"

Phoengap Push Notifications for Android and iOS

 

Wednesday, January 8, 2014

PhoneGap: Detect File Loaded from Phonegap or Not

/** * Determine whether the file loaded from PhoneGap or not */

 function isPhoneGap() { 
     return (cordova || PhoneGap || phonegap) 
     && /^file:\/{3}[^\/]/i.test(window.location.href) 
     && /ios|iphone|ipod|ipad|android/i.test(navigator.userAgent); 
}
 if ( isPhoneGap() ) { 
     alert("Running on PhoneGap!"); 
} else { 
     alert("Not running on PhoneGap!"); 
}

Thursday, December 12, 2013

Hybrid vs Native mobile apps



This is an interesting question.
Few years ago, now late Steve Jobs proclaimed that HTML5 is the future of web development. Ok this needs to be viewed in a broader context, at that point in time Apple was waging a war against Flash and HTML 5 was a unlucky winner.
Steve Jobs quote:
They are lazy, Jobs says. They have all this potential to do interesting things but they just refuse to do it. They don’t do anything with the approaches that Apple is taking, like Carbon. Apple does not support Flash because it is so buggy, he says. Whenever a Mac crashes more often than not it’s because of Flash. No one will be using Flash, he says. The world is moving to HTML5.

Friday, April 19, 2013

Get County from User Lat Long

In Mobile application how the server knows about the posted device country and response then as per the location.

Get the current location of the device and use google map api to get user location. Get location from the ipaddress is a worth thing now. because all the internet user use proxy network.

PHP:

<?php

$cur_lat =$_REQUEST['lat'];
$cur_lon = $_REQUEST['lon'];

Stop Copy Text from Phonegap Applications

Hello,

Phonegap application is based on the HTML, CSS and JQuery. So if the user double tap on the app content then it will select the text and give option to copy and select text.

So for the application privacy if app admin does not want to copy application text then here is a way to stop selection of text.

Friday, April 12, 2013

Get Distance Between Two Lat Long

Create function to calculate distance. and pass lat long of first place and second place. and one parameter for the distance type.

function calculateDistance($lat1,$lng1,$lat2,$lng2,$miles = true)
{
    $pi80 = M_PI / 180;
    $lat1 *= $pi80;
    $lng1 *= $pi80;
    $lat2 *= $pi80;
    $lng2 *= $pi80;

Monday, April 1, 2013

Image store in Database.

Get the image URL that you want to store in the database.

$file= "http://sitename.com/image1.jpg";

$imgdata = base64_encode(file_get_content($file));

Above syntax give you a image in encoded formate. Store image data as a text in the database.

Use of image data in html app.
Get data from the database and append "data:image/jpeg:base64," before the data string like below:

data:image/jpeg:base64,imgdata

Use appended string as a source of the image like below:

<img src="data:image/jpeg:base64,skadadjsiweryerjtkHRUWNHDDhASDJKKSDHD=" />

It will display image to the application.. in mobile applications does not need to load image from the server. and its also use for the offline application.

Thursday, January 31, 2013

Numbers convert to currency formate

Copy below function in your js.

function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num)) num = "0";
  // sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10) cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
    return ( num + '.' + cents);
}

call function to get currency formate:
$('#test').html(formatCurrency('123456.98'));

Output:
123,456.98

Cheers...