Showing posts with label ios. Show all posts
Showing posts with label ios. Show all posts

Sunday, February 7, 2021

State management in React Native Part-2

Context can only store a single value, not an indefinite set of values each with its own consumers. 

In order to solve this problem, we needed a way to provide a global state that all components, regardless of how deeply nested they are, could access. React Hooks and Redux are ways to manage state in a React app.

In Previous blog we've got mentioned about Context API, now will see in information about the Redux.

Redux:

The Redux describes it as a predictable state container for JavaScript applications that helps us to write programs that behave constantly, run in several depths and widths of elements, and are easy to check.

Redux is a state control library used to store and manage the state of a react software in a centralized position. Redux abstracts all states from the app into one globalized state object in order that any component and any a part of the app can get access to the different properties of the global state. Redux is separate from React and there are libraries to combine Redux into React apps.

Friday, February 5, 2021

State management in React Native Part-1

It is best to use React's built-in state management capabilities rather than external global state for smaller Apps, but default React state has certain limitations: Component state can only be shared by pushing it up to the common ancestor, but this might include a huge tree that then needs to re-render.

Context api with React Hooks

The React Context API is React’s approach of managing state in more than one elements that are not directly connected. You can create your individual custom hooks to avoid repetition and make code cleaner. Context supplies a way to pass data in the course of the component tree without having to pass props down manually at every level. Custom hooks are customary JavaScript functions which is able to use different React hooks.

Without Hooks, the Context API may no longer seem like much when compared to Redux, however mixed with the useReducer Hook, we have now an answer that finally solves the state management drawback.
Custom hooks resolve the problem of fending off repetition and make code cleaner. Context supplies a strategy to move information in the course of the component tree with no need to go props down manually at each and every stage.

Tuesday, June 20, 2017

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];



👍

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, January 22, 2014

Create a SSL Certificate for Apple Push Notifications Service

To enable push notifications in your app, it needs to be signed with a provisioning profile that is configured for push. In addition, your server needs to sign its communications to APNS with an SSL certificate.
The provisioning profile and SSL certificate are closely tied together and are only valid for a single App ID. This is a protection that ensures only your server can send push notifications to instances of your app, and no one else.
As you know, apps use different provisioning profiles for development and distribution. There are also two types of push server certificates:
  • Development. If your app is running in Debug mode and is signed with the Development provisioning profile (Code Signing Identity is “iPhone Developer”), then your server must be using the Development certificate.
  • Production. Apps that are distributed as Ad Hoc or on the App Store (when Code Signing Identify is “iPhone Distribution”) must talk to a server that uses the Production certificate. If there is a mismatch between these, push notifications cannot be delivered to your app.
In this tutorial, you won’t bother with the distribution profiles and certificates and just use the ones for development.

Generating the Certificate Signing Request (CSR)

Remember how you had to go to the iOS Provisioning Portal and make a Development Certificate after you signed up for the iOS Developer Program? If so, then these next steps should be familiar. Still, I advise you to follow them exactly. Most of the problems people have with getting push notifications to work are due to problems with the certificates.
Digital certificates are based on public-private key cryptography. You don’t need to know anything about cryptography to use certificates, but you do need to be aware that a certificate always works in combination with a private key.
The certificate is the public part of this key pair. It is safe to give it to others, which is exactly what happens when you communicate over SSL. The private key, however, should be kept… private. It’s a secret. Your private key is nobody’s business but your own. It’s important to know that you can’t use the certificate if you don’t have the private key.
Whenever you apply for a digital certificate, you need to provide a Certificate Signing Request, or CSR for short. When you create the CSR, a new private key is made that is put into your keychain. You then send the CSR to a certificate authority (in this case that is the iOS Developer Portal), which will generate the SSL certificate for you based on the information in the CSR.
Open Keychain Access on your Mac (it is in Applications/Utilities) and choose the menu option Request a Certificate from a Certificate Authority….
Requesting a certificate with Keychain Access
If you do not have this menu option or it says “Request a Certificate from a Certificate Authority with key”, then download and install the WWDR Intermediate Certificate first. Also make sure no private key is selected in the main Keychain Access window.
You should now see the following window:
Generating a certificate sign request with Keychain Access
Enter your email address here. I’ve heard people recommended you use the same email address that you used to sign up for the iOS Developer Program, but it seems to accept any email address just fine.
Enter “PushChat” for Common Name. You can type anything you want here, but choose something descriptive. This allows us to easily find the private key later.
Check Saved to disk and click Continue. Save the file as “PushChat.certSigningRequest”.
If you go to the Keys section of Keychain Access, you will see that a new private key has appeared in your keychain. Right click it and choose Export.
Exporting your private key with keychain access
Save the private key as PushChatKey.p12 and enter a passphrase.
For the convenience of this tutorial, I used the passphrase “pushchat” to protect the p12 file but you should really choose something that is less easy to guess. The private key needs to be a secret, remember? Do choose a passphrase that you can recall, or you won’t be able to use the private key later.

Making the App ID and SSL Certificate

Log in to the iOS Dev Center and “Select the Certificates, Identifiers and Profiles” from the right panel.
Certificates Identifies and Profiles
You will be presented with the following screen (Doesn’t the new dev center UI look sleek :))
Certificates, Identifiers and Profiles section
Since you’re making an iOS app select Certificates in the iOS Apps section.
Now, you are going to make a new App ID. Each push app needs its own unique ID because push notifications are sent to a specific application. (You cannot use a wildcard ID.)
Go to App IDs in the sidebar and click the + button.
Create App ID
Fill the following details:
  • App ID Description: PushChat
  • App Services Check the Push Notifications Checkbox
  • Explicit App ID: com.hollance.PushChat
It is probably best if you choose your own Bundle Identifier here – com.yoursite.PushChat – instead of using mine. You will need to set this same bundle ID in your Xcode project. After you’re done filling all the details press the Continue button. You will be asked to verify the details of the app id, if everything seems okay click Submit
Hurray! You have successfully registered a new App ID.
Registration Complete
In a few moments, you will generate the SSL certificate that your push server uses to make a secure connection to APNS. This certificate is linked with your App ID. Your server can only send push notifications to that particular app, not to any other apps.
After you have made the App ID, it shows up like this in the list:
List of App Ids
Select the PushChat app ID from the list. This will open up an accordion as shown below:
Push App accordion
Notice in the “Push Notification” row, there are two orange lights that say “Configurable” in the Development and Distribution column. This means your App ID can be used with push, but you still need to set this up. Click on the Setting button to configure these settings.
App ID Settings
Scroll down to the Push Notifications section and select the Create Certificate button in the Development SSL Certificate section.
Create Development Certificate
The “Add iOS Certificate” wizard comes up:
Add iOS Certificate
The first thing it asks you is to generate a Certificate Signing Request. You already did that, so click Continue. In the next step you upload the CSR. Choose the CSR file that you generated earlier and click Generate.
Generate Certificate
It takes a few seconds to generate the SSL certificate. Click Continue when it’s done.
Now click Download to get the certificate – it is named “aps_development.cer”.
Click Download
As you can see, you have a valid certificate and push is now available for development. You can download the certificate again here if necessary. The development certificate is only valid for 3 months.
When you are ready to release your app, repeat this process for the production certificate. The steps are the same.
Note: The production certificate remains valid for a year, but you want to renew it before the year is over to ensure there is no downtime for your app.
You don’t have to add the certificate to your Keychain, although you could if you wanted to by double-clicking the downloaded aps_development.cer file. If you do, you’ll see that it is now associated with the private key.

Making a PEM File

So now you have three files:
  • The CSR
  • The private key as a p12 file (PushChatKey.p12)
  • The SSL certificate, aps_development.cer
Store these three files in a safe place. You could throw away the CSR but in my opinion it is easier to keep it. When your certificate expires, you can use the same CSR to generate a new one. If you were to generate a new CSR, you would also get a new private key. By re-using the CSR you can keep using your existing private key and only the .cer file will change.
You have to convert the certificate and private key into a format that is more usable. Because the push part of our server will be written in PHP, you will combine the certificate and the private key into a single file that uses the PEM format.
The specifics of what PEM is doesn’t really matter (in fact, I have no idea) but it makes it easier for PHP to use the certificate. If you write your push server in another language, these following steps may not apply to you.
You’re going to use the command-line OpenSSL tools for this. Open a Terminal and execute the following steps.
Go to the folder where you downloaded the files, in my case the Desktop:
$ cd ~/Desktop/
Convert the .cer file into a .pem file:
$ openssl x509 -in aps_development.cer -inform der -out PushChatCert.pem
Convert the private key’s .p12 file into a .pem file:
$ openssl pkcs12 -nocerts -out PushChatKey.pem -in PushChatKey.p12
Enter Import Password: 
MAC verified OK
Enter PEM pass phrase: 
Verifying - Enter PEM pass phrase: 
You first need to enter the passphrase for the .p12 file so that openssl can read it. Then you need to enter a new passphrase that will be used to encrypt the PEM file. Again for this tutorial I used “pushchat” as the PEM passphrase. You should choose something more secure.
Note: if you don’t enter a PEM passphrase, openssl will not give an error message but the generated .pem file will not have the private key in it.
Finally, combine the certificate and key into a single .pem file:
$ cat PushChatCert.pem PushChatKey.pem > ck.pem
At this point it’s a good idea to test whether the certificate works. Execute the following command:
$ telnet gateway.sandbox.push.apple.com 2195
Trying 17.172.232.226...
Connected to gateway.sandbox.push-apple.com.akadns.net.
Escape character is '^]'.
This tries to make a regular, unencrypted, connection to the APNS server. If you see the above response, then your Mac can reach APNS. Press Ctrl+C to close the connection. If you get an error message, then make sure your firewall allows outgoing connections on port 2195.
Let’s try connecting again, this time using our SSL certificate and private key to set up a secure connection:
$ openssl s_client -connect gateway.sandbox.push.apple.com:2195 
    -cert PushChatCert.pem -key PushChatKey.pem
Enter pass phrase for PushChatKey.pem: 
You should see a whole bunch of output, which is openssl letting you know what is going on under the hood.
If the connection is successful, you should be able to type a few characters. When you press enter, the server should disconnect. If there was a problem establishing the connection, openssl will give you an error message but you may have to scroll up through the output to find it.
Note: There are two different APNS servers: the “sandbox” server that you can use for testing, and the live server that you use in production mode. Above, we used the sandbox server because our certificate is intended for development, not production use.

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

 

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 File Last Modified Date-Time

<?php

$filename = 'somefile.txt';
if (file_exists($filename)) {
    echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}

?>

this file modify date is used for the mobile application to get updates are available or not on the server file.

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.

Friday, January 25, 2013

Access-Control-Allow-Origin. issue on Phonegap JqueryMobile

When i ajax call to get or post some Data from Server, Some times I found error like below.

XMLHttpRequest cannot load file://localhost/Users/bhumika/Documents/phonegap-2.2.0/lib/ios/bin/****/www/js/data.json. Origin null is not allowed by Access-Control-Allow-Origin.

to Solve above error write below syntax in your device ready function.

$.support.cors = true;
$.mobile.allowCrossDomainPages = true;

Or  

Write Below syntax in PHP file to the server.
 
header('Access-Control-Allow-Origin: *');
Cheers....

Friday, December 28, 2012

Stop Bounce webapp in iphone

To stop bounce iphone view on the phonegap because iphone native app does not bounce
Go to the cordova.plist  file and you can see the key name "UIWebViewBounce" its default value id yes.  set value "NO".



and check app.. cheers.