Quantcast
Channel: Yudiz Solutions Ltd.
Viewing all 595 articles
Browse latest View live

Android Push Notification Using Firebase

$
0
0

Firebase is a powerful platform for building mobile and web based applications. It helps developer to build high-quality apps and games. Firebase provides facilities of  real time database and synchronization, user authentication service, analytical tools, hosting web site, send notification and many more. Before the Google I/O 2016 event, we had worked with  Google Cloud Messaging service to send messages or notifications from the server to the clients or mobile app users. In Google I/O 2016, Google introduced the firebase cloud messaging.

Steps for sending message using firebase.

Step 1:

First of All, we create project on google firebase console, Here is the link of it: https://console.firebase.google.com/

image00

Add project name and country name in new project. After the firebase dashboard is visible to you, select appropriate technology. We needed for android so we clicked android app icon.

image04

After that, below screen will be visible. Add package name of new project and SHA-1 key to the Project.

image03

Once you submit all the information, firebase gives you google-services.json which contains all information regarding your project. Copy this file and paste this file into your app directory e.g. //app/(paste here).

image02

Step 2:

Now let us start the coding part. After creating new project, copy google-service.json file. Add google play services. Open project level build.gradle file and place below line and sync project.

// google services
classpath ‘com.google.gms:google-services:3.0.0’

Example:

dependencies {
   classpath 'com.android.tools.build:gradle:2.1.0'
   classpath 'com.google.gms:google-services:3.0.0'
}

Step 3:

Now open your app level build.gradle file and paste below line

  • add apply plugin: ‘com.google.gms.google-services’
  • compile ‘com.google.firebase:firebase-messaging:9.0.2’

press Sync now.

Example:

fdR88blS-wU:APA91bETjBJCZD-MGf5F7LUl58_x4OP9ilQa0YZ3vcEs8Bwt15_CderfFtHA7cEWPGH5WmkS0C77hyVYIG-zUlmhZK9eSk4zvY5TzaCZYnMySgMZm4WCIDFEG19P5xt-qy6bibY2m9x-
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
   compileSdkVersion 24
   buildToolsVersion "24.0.1"

   defaultConfig {
       applicationId "firebase.sample.yudiz.firebasesample"
       minSdkVersion 15
       targetSdkVersion 24
       versionCode 1
       versionName "1.0"
   }
   buildTypes {
       release {
           minifyEnabled false
           proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
       }
   }
}

dependencies {
   compile fileTree(dir: 'libs', include: ['*.jar'])
   testCompile 'junit:junit:4.12'
   compile 'com.android.support:appcompat-v7:24.2.1'
   compile 'com.google.firebase:firebase-messaging:9.0.2'
}

Step 4:

Create user registration service that extends by FirebaseInstanceIdService and override onTokenRefresh method which fire when new token is generated. It contains token and token helps to send notification. If we want to send a particular notification to a particular user then token will help to identify users.

Sample code is below :

public class FirebaseRegistation extends FirebaseInstanceIdService {

   private static final String TAG = "FirebaseApp";

   @Override
   public void onTokenRefresh() {

       //Getting registration token of FCM
       String refreshedToken = FirebaseInstanceId.getInstance().getToken();

       //Displaying token on your logcat
       Log.d(TAG, "Refreshed token: " + refreshedToken);

       //send FCM token to web service
       sendRegistrationToServer(refreshedToken);

   }

   private void sendRegistrationToServer(String token) {
       //You can implement this method to store the token on your server for your further implementation
       //Not required for current project
   }
}

Step 5:

Create message service that extends FirebaseMessagingService which received message from firebase and display to the user. It is required to override onMessageReceived method with RemoteMessage object. So RemoteMessage give notification object for accessing notification in App.

Sample code is below :

public class FirebaseMessaging extends FirebaseMessagingService {

   private static final String TAG = "FireBaseMessage";

   @Override
   public void onMessageReceived(RemoteMessage remoteMessage) {

       RemoteMessage.Notification notification = remoteMessage.getNotification();
       Log.d(TAG, "Notification Message Body: " + notification.getBody());

       //Calling method to generate notification
       sendNotification(notification.getBody());

   }

   //This method is only for generating push notification
   private void sendNotification(String messageBody) {
       Intent intent = new Intent(this, MainActivity.class);
       intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
       PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
               PendingIntent.FLAG_ONE_SHOT);

       NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
               .setSmallIcon(R.mipmap.ic_launcher)
               .setContentTitle("Firebase Notification")
               .setContentText(messageBody)
               .setAutoCancel(true)
               .setContentIntent(pendingIntent);

       NotificationManager notificationManager =
               (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

       notificationManager.notify(0, notificationBuilder.build());
   }
}

Step 6:

Declare all services in manifest file with permissions.

Sample code is below :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="firebase.sample.yudiz.firebasesample">

   <uses-permission android:name="android.permission.INTERNET"/>
   <application
       android:allowBackup="true"
       android:icon="@mipmap/ic_launcher"
       android:label="@string/app_name"
       android:supportsRtl="true"
       android:theme="@style/AppTheme">
       <activity android:name=".MainActivity">
           <intent-filter>
               <action android:name="android.intent.action.MAIN" />

               <category android:name="android.intent.category.LAUNCHER" />
           </intent-filter>
       </activity>

       <service android:name=".services.FirebaseMessaging">
           <intent-filter>
               <action android:name="com.google.firebase.MESSAGING_EVENT" />
           </intent-filter>

       </service>
       <service android:name=".services.FirebaseRegistation">
           <intent-filter>
               <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
           </intent-filter>

       </service>
   </application>

</manifest>

Step 7:

Now run application and test notification message. For Testing purpose, Firebase provided facilities of it. Look in the below screen, click it is your project structure in firebase. Click Notifications and get console of sending notification for testing. Just type message, Select App and send it. Enjoy…!

image06

Send Message Screen :
image05

Step 8:

Finally got Notification in Application . Yuppy ….!!!

image01

Sachin Patel

Sachin Patel | Android Developer

I am an Android Developer at Yudiz Solutions Pvt. Ltd. - a mobile App Development company. I am passionate about android app development and like adopting new technologies to maximize development efficiency and produce innovative applications.

Apple membership programs & create certificate, profile

$
0
0

In this blog we are going to learn how to create, install and export certificates and how to create provisioning profiles for your application. but before this we need to get knowledge about different types of membership programs for better understanding.

Understanding Apple Membership Programs

Apple Developer Program provides everything you need to build and distribute apps to Apple customers around the world.

See below image.

1

There are multiple types of membership programs available. As per your requirements you can enroll for individual program, organization program or educational institutions programs. Let’s start with organization.

Organizations

In organization there are 3 programs – developer, enterprise and MFi.

Apple Developer Program. [ 99 USD per year ]
  • If you’re an organization interested in creating apps for distribution on the App Store for apple devices, enroll in the Apple Developer Program.
  • Organizations can sell apps using their legal entity name.
  • D-U-N-S number must required during the enrollment process.   [    The D-U-N-S Number is a unique nine-digit number that identifies business entities on a location-specific basis. Assigned and maintained by Dun & Bradstreet (D&B), the D-U-N-S Number is widely used as a standard business identifier. ]
Apple Developer Enterprise Program [ 299 USD per year ]
  • In enterprise program organizations can not distribute/publish apps to the App Store
  • If your organization is looking to create own apps and distribute to your organization’s employee, enroll in the Apple Developer Enterprise Program.
  • D-U-N-S number must required.
MFi Program [ free of cost ]
  • Enroll this program if your companies manufacture electronic accessories that connect to Apple devices.

Individuals

Apple Developer Program. [ 99 USD per year ]
  • If you are an individual person and want to distribute your applications to the App Store then enroll in this Apple Developer Program.
  • Developers enrolled as individuals, will sell apps on the App Store using their personal name.
  • No need of D-U-N-S number during the enrollment process.

Educational Institutions

iOS Developer University Program.  [ free of cost ]
  • This is a free developer program for higher education institutions looking to introduce iOS development into their curriculum.
  • Any faculty and student can get access to the tools and resources needed to develop and install apps on Apple devices.
  • D-U-N-S number must required.

Comparison of Programs

See bellow image, you can compare and get idea how all programs are different from each other.

2

Create Certificate

To create a development or production certificate we will need CSR file. so, first of all let’s create certificate Signing Request(CSR).

Create CSR File:

Open Finder, and then open Keychain Access from the Utilities folder.

3

Next, open Keychain Access > Certificate Assistant > Request a Certificate From a Certificate Authority.

4

Enter the email address, and enter a common name. The common name can be anything you want. Check Saved to disk and then click Continue.

5

Give your CSR a helpful descriptive name, and choose the location to save it on your hard drive, then click Save.

6

Create Development Certificate

To run an app on an iOS device you need to create it with a development or an Ad Hoc distribution provisioning profile. To create a development provisioning profile, you need a development certificate signed by Apple. With this development certificate, you can code sign an app during development in order to deploy it on device.

You can create a development certificate in the iOS Dev Center  only.

Step 1:

In the iOS Dev Center, click Certificates, Identifiers & Profiles. In the drop-down menu in the top left corner, verify that iOS, tvOS, watchOS is selected.

In the left-hand sidebar, select CertificatesDevelopment.  Click +

7

Step 2:

Select iOS App Development and click Continue.

8

Step 3:

On the About Creating a Certificate Signing Request (CSR) page, click Continue.

On the Generate your certificate page, click Choose File. upload CSR file which was created before. then click continue.

9

Step 4:

Click Download to download your certificate. Click Done

10

Create Production Certificate

To publish an app in the App Store or to distribute it to a limited number of devices, you need to build it with a distribution provisioning profile. To create a distribution provisioning profile, you need a production certificate signed by         Apple. With this production certificate, you can code sign an app for publishing to the App Store, for in-house distribution or for distribution to limited number of devices.

You can create a production certificate in the iOS Dev Center only.

Procedure
  1. In the iOS Dev Center, click Certificates, Identifiers & Profiles.
  2. In the drop-down menu in the top left corner, verify that iOS, tvOS, watchOS is selected.
  3. In the left-hand sidebar, select CertificatesProduction.
  4. Click +.
  5. Select the type of production certificate that you want to create and click Continue.
    • If you are enrolled in the iOS Developer Program, select App Store and Ad Hoc and click Continue.
    • If you are enrolled in the iOS Developer Enterprise Program, select In-House and Ad Hoc and click Continue.
  6. On the About Creating a Certificate Signing Request (CSR) page, click Continue.
  7. On the Generate your certificate page, click Choose File.
  8. Browse to the location where the CSR file for your certificate signing request is stored, select it and confirm the upload. [ If you don’t create CSR then, please see “Create CSR File” section of this tutorial]
  9. Click Continue.

Click Download to download your certificate.

Install & Export Certificates

Install:
  • To install certificates Drag the certificate file onto the Keychain Access icon, or double-click the certificate file.
  • Click the keychain pop-up menu, choose a keychain, then click OK.
  • If you’re asked to enter the name and password for an admin user on this computer, enter it.
  • now, open key chain you can see your certificate.

11

Export:
  • In the Keychain Access window, left side under Keychains, click login, under Category, click Certificates, and then, select your code signing certificate.
  • right click on selected certificate. as shown in below image, click on export certificates.

12

  • Give your certificate  a helpful descriptive name, and choose the location to save it on your hard drive, then click Save.

13

Maintaining Identifier and Provisioning Profile

App IDs:

Registering App IDs

  • Before you can create a provisioning profile, you need to have a registered App ID.
  • An app ID is a string used to specify an app, or set of apps. An app ID’s primary use is to specify which apps are authorized to be signed and launched.Let’s start to create App Id for your application.

In the iOS Dev Center, click Certificates, Identifiers & Profiles.

See the below image , In the drop-down menu in the top left corner, verify that iOS, tvOS, watchOS is selected. In the left sidebar, select IdentifiersApp IDs. then Click +.

14

In the next screen you will be asked to create the App ID you want to use as well as the description you want to give it.Type a description for your app in the App ID Description text box. The description is visible in the iOS dev center only and will help you identify your App ID in the list of identifiers that are available to your Apple developer account.

15

Select the type of App ID that you want to create and provide a bundle identifier.

  • To use one App ID with multiple provisioning profiles, register a wildcard App ID.
  • If you want to build and publish an app with a unique App ID identifier and provisioning profile, register an explicit App ID

16

After that you will be brought to the confirmation screen. click on register button once you looked over it. then click on Done button. Now App Id has been created.

Deleting App IDs

In the iOS Dev Center, click Certificates, Identifiers & Profiles.

  1. Under Identifiers, select App IDs.
  2. Select the App ID you want to delete, and click Edit.
  3. Scroll to the bottom of the page, and click Delete.
  4. Read the dialog that appears, and click Delete.

Editing App IDs

In the iOS Dev Center, click Certificates, Identifiers & Profiles.

  1. Under Identifiers, select App IDs.
  2. Select the App ID you want to delete, and click Edit.
  3. now make changes you want in App Id.
  4. Click Done.

NOTE: If you edit App ID then, need to regenerate the provisioning profiles that use the App ID.

Provisioning Profiles

Development Provisioning Profile

  • When you build an app with a development provisioning profile, you can debug it on device.
  • The development provisioning profile is the only provisioning profile that enables debugging on device.
  • With this type of provisioning profile, you can run your apps only on the devices included in the provisioning profile and you cannot publish apps in the App Store.
Requirements:
  • Verify that you have a certificate for development created for your Apple developer account.
  • Verify that you have registered an App ID for your app.
  • Verify that you have registered at least one device with your Apple developer account.
Steps:
  1. In the iOS Dev Center, click Certificates, Identifiers & Profiles.
  2. In the drop-down menu in the top left corner, verify that iOS, tvOS, watchOS is selected.
  3. In the left-hand sidebar, select Provisioning ProfilesDevelopment.
  4. Click +.
  5. Select iOS App Development and click Continue.
  6. Select an App ID to associate with the provisioning profile and click Continue.
  7. To be able to use one development provisioning profile across multiple apps, select a wildcard App ID, if available.
  8. Select one or more certificates for development to include in the provisioning profile and click Continue.
  9. Only certificates for development are listed.
  10. Select one or more devices to include in the provisioning profile and click Continue.
  11. Provide a name for the profile and click Continue.
  12. Click Download to download the provisioning profile.

Click Done.

App Store Distribution Provisioning Profile

  • In the App Store you can publish only apps created with an App Store distribution provisioning profile.
  • App Store distribution provisioning profiles do not contain provisioned devices.
  • You can not debug on device apps that are created with this type of provisioning profile.
Requirements:
  • Verify that you have a certificate for production created for your Apple developer account.
  • Verify that you have registered an App ID for your app.
Steps:
  1. In the iOS Dev Center, click Certificates, Identifiers & Profiles.
  2. In the drop-down menu in the top left corner, verify that iOS, tvOS, watchOS is selected.
  3. In the left-hand sidebar, select Provisioning ProfilesApp Store.
  4. Click +.
  5. Select App Store and click Continue.
  6. Select an App ID to associate with the provisioning profile and click Continue.
  7. To be able to use one development provisioning profile across multiple apps, select a wildcard App ID, if available.
  8. Select one or more certificates for production to include in the provisioning profile and click Continue.
  9. Only certificates for production are listed.
  10. Enter a name for the profile and click Continue.
  11. Click Download to download the provisioning profile.

Ad Hoc Distribution Provisioning Profile

  • If you want to send out your app for testing to selected users or to develop a private app which is available to a limited number of devices, you can create it with an Ad Hoc provisioning profile.
  • You cannot debug on device apps that are created with this type of provisioning profile.
Requirements:
  • Verify that you have a certificate for production created for your Apple developer account.
  • Verify that you have registered an App ID for your app.
  • Verify that you have registered at least one device with your Apple developer account.
Steps:
  • In the iOS Dev Center, click Certificates, Identifiers & Profiles.
  • In the drop-down menu in the top left corner, verify that iOS, tvOS, watchOS is selected.
  • In the left-hand sidebar, select Provisioning ProfilesDistribution.
  • Click +.
  • Select Ad Hoc and click Continue.
  • Select an App ID to associate with the provisioning profile and click Continue.
  • To be able to use one development provisioning profile across multiple apps, select a wildcard App ID, if available.
  • Select one or more certificates for production to include in the provisioning profile and click Continue.
  • Only certificates for production are listed.
  • Select the devices that you want to include in the provisioning profile and click Continue.
  • Provide a name for the profile and click Continue.
  • Click Download to download the provisioning profile.
  • Click Done.

In-House Distribution Provisioning Profile

  • If you want to develop and distribute apps privately within your company or to a selected number of end users, you can use a provisioning profile for in-house distribution.
  • When you build an app with a provisioning profile for in-house distribution, you can distribute the app outside of the App Store to the devices registered in your iOS Developer Enterprise Program.
  • You can use an in-house provisioning profile to build and code sign private company apps.
Requirements:
  • Verify that you have a certificate for production created for your Apple developer account.
  • Verify that you have registered an App ID for your app.
Steps:
  1. In the iOS Dev Center, click Certificates, Identifiers & Profiles.
  2. In the drop-down menu in the top left corner, verify that iOS, tvOS, watchOS is selected.
  3. In the left-hand sidebar, select Provisioning ProfilesDistribution.
  4. Click +.
  5. Select In House and click Continue.
  6. Select an App ID to associate with the provisioning profile and click Continue.
  7. To be able to use one development provisioning profile across multiple apps, select a wildcard App ID, if available.
  8. Select one or more certificates for production to include in the provisioning profile and click Continue.
  9. Only certificates for production are listed.
  10. Enter a name for the profile and click Continue.

Click Download to download the provisioning profile.

Editing Provisioning Profiles

In the iOS Dev Center, click Certificates, Identifiers & Profiles.

  1. Under Provisioning Profiles Select the develoment/Distribution profile as per requirement.
  2. at the bottom of view click Edit.17
  3. Make your changes to the provisioning profile, such as changing its name, adding certificates, or selecting a different set of devices.18
  4. click on Generate button.

Deleting Provisioning Profiles:

  1. Under Provisioning Profiles Select the development / Distribution profile as per requirement.
  2. Select the profile you want to Delete.
  3. at the bottom of view click Delete.
  4. Give confirmation to delete, click Delete button.

Creating your own iOS framework and distributed using CocoaPods

$
0
0

Click To Download Full Source Code

iOS: 10

Language: Swift 3

Xcode Version: 8

Mac OS: 10.11

Creating your Framework

Step 1: Create simple Xcode project

  • For this demo, first create a Xcode project by selecting a template for our project Cocoa Touch Framework from iOS tab.image18
  • Click next and Give your framework name and save to your diskimage18

Step 2: Change the build configuration to release mode of your framework

  • Select your framework target and Navigate to Product->Scheme->Edit Schemeimage18
  • You can see the Build configuration is set to Debug. It means that whenever you run this project it will create our framework in Debug mode so if we want to use this framework in our application we switch to Release mode.image18
  • Now if we run this project it will be ready for release

Step 3: Add new swift file to your project

  • Now we want to add some functionality in our framework so we add a swift file to the project. Right click on project folder and select New File
    image00
  • Select Swift File from iOS tab and click next
    image18
  • Give the name of file and save to your project directory
    image04

Step 4: Create our first class in swift file

  • Create class named YLog. This can actually be used inside our framework project however we want but we want to use this class outside the framework so we have to mark this class as public.
  • Write following code to your YLog.swift file:
    //1.
        private var isDebug: Bool!
        
        //2.
        public init() {
            self.isDebug = false
        }
        
        //3.
        public func setup(isDebug: Bool) {
            self.isDebug = isDebug
            print("Project is in Debug mode: \(isDebug)")
        }
        
        //4.
        public func YPrint<T>(value: T) {
            if self.isDebug == true {
                print(value)
            } else {
                //Do any stuff for production mode
            }
        }
  • The purpose of this YLog class is going to be if our application is in Debug mode we want to printing out debugger but our application is in production for presenting to appStore we don’t want to print this debugger because we can’t see them and also slow down the application performance.
  1. Create a variable named isDebug so we manage application is in debug or in production mode.
  2. We should add initialiser to our class. So in init() method we initialise debug variable and set it to false because just incase if you forgot to set your app to debug mode, the Logging framework automatically stop printing debugger. We actually need this init() method to set as public so we can initialise our variable from outside the framework.
  3. The setup() method is used to set the application mode, set to true means application in Debug mode and false means in Production mode.
  4. Now we create actual logging method called YPrint and this is going to be a generic. In this method if isDebug is set to true, we print out the value in debugger otherwise not because out app in production mode and you can do any stuff in else part.

Step 5: Run your project and find your framework

  • Run your project by pressing Command+R
  • Now you can see the framework in products folder. Right click on it and select show in finder

image19

  • Copy YLogging.framework file and paste it to your desktop.

image14

  • Close your framework project.

Step 6: Create new simple Xcode project to use the framework

  • Create a Xcode project by selecting a template for our project Single View Application from iOS tab.

image12

  • Click next and give name of project like FrameworkTest and save to your disk

image05

Step 7: Add framework in our application

  • Create a folder called as Frameworks in your project directory and drag your framework from desktop into this folder
    image08
  • Now select your targets and click on + button under the Embedded Binaries tab.
    image02
  • Click On Add other and navigate to your project directory and select your framework from Frameworks folder
    image01

Step 8: Import your framework and Setup debugging mode

  • Open AppDelegate.swift file and at top write import YLogging.
  • Create global variable  so we can use this logging framework anywhere in our application.
    let logger = YLog()
  • Call the setup() method of framework from didFinishlaunchingWithOptions method and set isDebug to true.
    logger.setup(isDebug: true)
  • So Now your AppDelegate.swift file looks like below:image13

Step 9: Use of YPrint method

  • Open ViewController.swift file and in viewDidLoad() write following code:
    logger.YPrint(value: “Working fine…”)
  • Run your project and see the following output in debugger:
    image07
  • Now change the debug mode to false using setup() method from AppDelegate and see the output.
    logger.setup(isDebug: false)
    image07

Distributing your framework using CocoaPods

CocoaPods manages library dependencies for your Xcode projects. The dependencies for your projects are specified in a single text file called a Podfile. CocoaPods will resolve dependencies between libraries, fetch the resulting source code, then link it together in an Xcode workspace to build your project. Ultimately the goal is to improve discoverability of, and engagement in, third party open-source libraries by creating a more centralised ecosystem.

Here we are going to make our framework into a pod, so we are distributing the code, resolving the dependencies, including and building the framework source, and easily sharing it with our organization.

Step 1: Remove current framework from your project

  • Select YLogging.framework from the project navigator and delete it.
  • Choose Move To Trash to permanently remove framework from your project.

Step 2: Install CocoaPods

  • If you are not familiar with CocoaPods before, you’ll need to follow a brief installation process using CocoaPods Installation Guide before going any further.

Step 3: Create the Pod of your framework

  • Open terminal in YLogging project directory and run following command:
    pod spec create YLogging
  • This command creates the file YLogging.podspec in current directory. Right click on this file and open in text editor.
  • Remove all the text from that file and paste following lines  for commonly use settings for pod configuration:
    Pod::Spec.new do |s|
              #1.
              s.name               = "YLogging"
              #2.
              s.version            = "1.0.0"
              #3.  
              s.summary         = "Sort description of 'YLogging' framework"
              #4.
              s.homepage        = "http://yudiz.com"
              #5.
              s.license              = "MIT"
              #6.
              s.author               = "AKanjariya"
              #7.
              s.platform            = :ios, "10.0"
              #8.
              s.source              = { :git => "URL", :tag => "1.0.0" }
              #9.
              s.source_files     = "YLogging", "YLogging/**/*.{h,m,swift}"
        end
  • Save the file and now you have a workable development Podspec.
  1. Specify the name of pod
  2. Version of pod
  3. Short description of your pod
  4. Point to a project page for the framework.
  5. Specify this iOS frameworks tutorial code using an MIT License
  6. Name of that person credited and contacted for this framework.
  7. Specify the platform which can use this framework.
  8. Setup the URL for link to the GitHub repository. When you’re ready to share the pod, replace URL with your GitHub repository url, so this will be a link to the GitHub repository and the commit tag for this version.
  9. Specify the source files folder and types of files which you want to add into pod.

Step 4: Use pod into your application

  • Now our pod is ready to use. Test it out by implementing in the FrameworkTest app.
  • Go to terminal and navigate to the FrameworkTest directory and run following command
    pod init
  • This will create a pod file into current directory. Open That file into text editor and add the following line under the comment, # Pods for FrameworkTest:
    pod ‘YLogging’, :path => ‘../YLogging’
  • Save this file and run following command in terminal:
    pod install
  • With this command, you’re searching the CocoaPods repository and downloading any new or updated pods that match the Podfile criteria. and it will create a FrameworkTest.xcworkspace file. Use this file from now on instead of the .xcodeproj file because it has the reference to the Pods project and the app project.
  • Open FrameworkTest.xcworkspace and run the project.

Step 5: Create GitHub Repository

  • Here you can publish your pod on GitHub and use like a third party framework.
  • If you don’t already have a GitHub account, create one.
  • Create a new repository to host the pod. Specify the name of repository here YLogging, you can name it whatever you want. Select Swift as .gitignore language and MIT as licence.
    image11
  • Click on Create Repository. From the dashboard page of your repository copy the HTTPS link.
    image06

Step 6: Add your framework to GitHub

  • Open your YLogging.podspec file from YLogging folder and update the s.source line. Replace URL with your repository link copied from GitHub dashboard
  • Go to terminal and navigate to YLogging folder and run following commands:
    git init
        git remote add origin GitHub_URL
        git fetch --all
        git pull origin master    
        git add .
        git commit -m "Initial commit"
        git push -u origin master
  • You need to tag the repository so it matches the Podspec. Run this command to set the tags:
    git tag 1.0.0    
    git push --tags
  • Now your framework is on your GitHub repository. Go to the repository on browser and refresh to see changes:
    image15

Step 7: Update your podfile.

  • Update your podfile in the FrameworkTest directory. Replace the existing pod line with:
    pod ‘YLogging’, :git => ‘URL’, :tag => ‘1.0.0’
  • Replace URL with your GitHub Link.
  • Go to terminal and navigate to FrameworkTest directory and run following command to update your pod file:
    pod update
  • Now the code will be downloaded the framework from the GitHub repository.

Customization in WordPress

$
0
0

Currently, WordPress is the widely used Content Management System in the world and is being utilized by nearly 75 million websites. Here I am trying to bring in front of you few primary customization required while you are developing your website in WordPress.

How to make custom widget area?

To make custom widget area, you need to write following code in your functions.php file which could be either in parent/child theme.

Code for functions.php:

register_sidebar(array(
        'id' => 'widget-id',     
        'name' => 'widget name',
        'description' => 'description',
        'before_widget' => '<div id="%1$s" class="widget %2$s">',
        'after_widget' => '</div>',
        'before_title' => '<h4 class="widgettitle">',
        'after_title' => '</h4>',
));

Code to be written in php file where you want to display the content of the created widget:

<?php dynamic_sidebar('widget-id'); ?>

Screenshot-1

Screenshot-1.1

How to allow php code in widget?

To allow php code in widget you need to add following code into your function file i.e functions.php

Code:

function execute_php($html){
     if(strpos($html,"<"."?php")!==false){ ob_start(); eval("?".">".$html);
          $html=ob_get_contents();
          ob_end_clean();
     }
     return $html;
}
add_filter('widget_text','execute_php',100);

Screenshot-2

Screenshot-2.1

How to enable shortcode in widget?

To enable shortcode in widget you need to write below code in your functions.php file.

Code:

add_filter('widget_text', 'do_shortcode');

Screenshot-3

Screenshot-3.1

How to create custom menu?

To create custom menu in wordpress follow the below steps.

You need to write the below code in function file:

function my_custom_menus() {
    register_nav_menus(
            array(
                    'footer-menu' => __( 'Footer Menu' )
            )
    );
}
add_action( 'init', 'my_custom_menus' );

Write the below code in php file where you want to display the custom menu.

Screenshot-3

Screenshot-3.1

How to limit the length of the excerpt and change the by default read more excerpt string i.e […]?

You need to write the following code into your function file.

Code to limit the length of excerpt is as below:

function custom_excerpt_length( $length ) {
    return 30;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );

Code to change the read more excerpt string is as below:

function wpdocs_excerpt_more( $more ) {
    return '...';
}
add_filter( 'excerpt_more', 'wpdocs_excerpt_more' );

Screenshot-3

Screenshot-3.1

How to include your parent theme’s stylesheet into child theme?

There are two ways we can include to do this:

  1. You need to write below code into your child theme’s stylesheet.
    @import url("../your-theme-name/style.css");
  2. You need to write the below mention code into your function file of the child theme.
    add_action( 'wp_enqueue_scripts', 'enqueue_parent_styles' );
          function enqueue_parent_styles() {
          wp_enqueue_style( 'parent-style',   get_template_directory_uri().'/style.css');
    }

Second method is more preferable than first method as in first one all the css that are included will be downloaded consecutively which will reduce the page speed.

How to create custom templates for pages, header and footer?

Custom Page Template:

To create a template for a particular page, first select the suitable template then make a copy of it and place it in child theme. Here I am trying to make a template file for landing page.

Custom Header:

To create custom header for any page you need to make a copy of header.php and rename it like header-landing.php (you can add any word after header-).Here I am creating header for landing page so I will name it header-landing.php

Custom Footer:

To create custom footer for any page you need to make a copy of footer.php and rename it like footer-landing.php (you can add any word after footer-).Here I am creating footer for landing page so I will name it footer-landing.php

Screenshot-8

Screenshot-8.1

Screenshot-8.2

Creating Tableview With Section Indexes

$
0
0

Overview

UILocalizedIndexedCollation is a class that helps to organise data in table views with section index titles in a locale-aware manner. Rather than creating the object directly, a shared instance corresponding to the current locale supported by your application is accessed, with UILocalizedIndexedCollation +currentCollation.

The first task for UILocalizedIndexedCollation is to determine what section index titles to display for the current locale, which can be read from the sectionIndexTitles property.

There are different section index titles for different locale. Like

en_US locale has section titles are : A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, #
AR_sa locale has section titles are : A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, آ, ب, ت, ث, ج, ح, خ, د, ذ, ر, ز, س, ش, ص, ض, ط, ظ, ع, غ, ف, ق, ك, ل, م, ن, ه, و, ي, #

To prepare the data for a section index, your view controller creates a indexed-collation object and then, for each model object that is to be indexed, calls section(for:collationStringSelector:). This method determines the section in which each of these objects should appear and returns an integer that identifies the section.

The table-view controller then puts each object in a local array for its section. For each section array, the controller calls the sortedArray(from:collationStringSelector:) method to sort all of the objects in the section. The indexed-collation object is now the data store that the view controller uses to provide section-index data to the table view.

Now, here is a demo project and code :

We have a Model class Contact like as:

class Contact {
var name: String!
var mobile: String!
init(name: String, mob: String) {
self.name = name
self.mobile = mob
}
}

In view controller we have a collection of contacts (which will be shown in tableview in alphabetical sections) like as :

var contacts = [Contact]()

//In viewDidLoad method i have created some contacts and append them into contacts array.

override func viewDidLoad() {

super.viewDidLoad()

//1. Create some contact objects for adding in contacts array.

let contact1 = Contact(name: "Anuska", mob: "123434")

let contact2 = Contact(name: "Anuj Sinha", mob: "2321234")

let contact3 = Contact(name: "Maria", mob: "343434")

let contact4 = Contact(name: "Jacob", mob: "34454545")

let contact5 = Contact(name: "Macculam", mob: "455656")

let contact6 = Contact(name: "Sophia", mob: "4567890")

//2. Add all these contacts in contacts array

self.contacts = [contact1, contact2, contact3, contact4, contact5, contact6]

}

In the first part of the demo, we have created a tableview without sections.

Here is the code for TableViewDataSource and TableViewDelegate :
Before implementing tableview datasource, create a tableview cell for contact like below :

Add this code in your ViewController file (Out of ViewContoller class scope)

class ContactCell: UITableViewCell {

@IBOutlet var lblName: UILabel!

@IBOutlet var lblMobile: UILabel!

}

extension ViewController : UITableViewDataSource, UITableViewDelegate {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return contacts.count

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! ContactCell

let contact = contacts[indexPath.row]

cell.lblName.text = contact.name

cell.lblMobile.text = contact.mobile

return cell

}

}

Now Run your app and see the output screen : it looks like below screenshot

ScreenShot1

Next, for section wise table view, we need to create partition of contacts array in alphabetical sections.

For this we have used the UILocalizedIndexCollation class.
Add bellow line of code in your ViewController

let collation = UILocalizedIndexedCollation.current()

+current() func create a locale collation object, by which we can get section index titles of current locale.

Add this extension of UILocalizedIndexedCollation in your project

extension UILocalizedIndexedCollation {
//func for partition array in sections
func partitionObjects(array:[AnyObject], collationStringSelector:Selector) -> [AnyObject] {
var unsortedSections = [[AnyObject]]()
//1. Create a array to hold the data for each section
for _ in self.sectionTitles {
unsortedSections.append([]) //appending an empty array
}
//2. put each objects into a section
for item in array {
let index:Int = self.section(for: item, collationStringSelector:collationStringSelector)
unsortedSections[index].append(item)
}
//3. sort the array of each sections
var sections = [AnyObject]()
for index in 0 ..< unsortedSections.count {
sections.append(self.sortedArray(from: unsortedSections[index], collationStringSelector: collationStringSelector) as AnyObject)
}
return sections
}
}

Above extension have a func partitionObjects(_:) , which contain code in 3 parts, each one is describe in code.
This func will return a array of sorted arrays in alphabetical order.

Now we have used this func from ViewController for partition of contacts array in sections.
Add below line of code in ViewController :

var contactsWithSections = [[Contact]]()

In this array, each item contains the array of Contact objects, which is used to bind with tableview.

Now we should need to modify the viewDidLoad func by adding below line of code :

contactsWithSections = collation.partitionObjects(array: self.contacts, collationStringSelector: #selector(getter: Contact.name)) as! [[Contact]]

Now viewDidLoad func looks like as below:

override func viewDidLoad() {
super.viewDidLoad()
//1. create some contact objects for adding in contacts array.
let contact1 = Contact(name: "Anuska", mob: "123434")
let contact2 = Contact(name: "Anuj Sinha", mob: "2321234")
let contact3 = Contact(name: "Maria", mob: "343434")
let contact4 = Contact(name: "Jacob", mob: "34454545")
let contact5 = Contact(name: "Macculam", mob: "455656")
let contact6 = Contact(name: "Sophia", mob: "4567890")
//2. add all these contacts in contacts array
self.contacts = [contact1, contact2, contact3, contact4, contact5, contact6]
//3. Create sections of contacts using collation object
contactsWithSections = collation.partitionObjects(array: self.contacts, collationStringSelector: #selector(getter: Contact.name)) as! [[Contact]]
}

Here collation.partitionObjects is used to partition your collection into sections, which needs two parameters, first parameter is a array and second parameter is a Selector.

Parameters:

  1. Array: an array to which you want to partition into sections.
  2. Selector: Selector is used to grouped your collection into sections. (like : name, title, descriptions of the array items’s object)

Make sure you should pass a string property or func (which returns a string) as a Selector.

Another thing which you should need to know is that, the property or func which you have to used as Selector should be @objc type.

In this example, i have used name property of Contact class as Selector. To make the Contact class as objective c type, Contact class should inherited from NSObject class.

I have replaced Contact class with below code:

class Contact : NSObject {
var name: String!
var mobile: String!
init(name: String, mob: String) {
self.name = name
self.mobile = mob
}
}

Now next step, to create the section tableview, we need to bind the tableview datasource with contactsWithSections array.
For this, i have replaced tableview datasource code with below code :

func numberOfSections(in tableView: UITableView) -> Int {
return contactsWithSections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return contactsWithSections[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! ContactCell
let contact = contactsWithSections[indexPath.section][indexPath.row]
cell.lblName.text = contact.name
cell.lblMobile.text = contact.mobile
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return collation.sectionTitles[section]
}

Now run the project and see the output. Here is the screenshot of output screen

ScreenShot2

In above screenshot, you can see the tableview with sections. Each contacts are shown in its proper section titles. But there are some unexpected sections, which does not have any contact items in it.
To remove these empty item sections we need to modify our code once again.

First of all we have to modify the returns type of partitionObjects(_:) func of UILocalizedIndexedCollation extension.
For that i have replaced old partitionObjects(_:) func with below new func :

//func for partition array in sections
func partitionObjects(array:[AnyObject], collationStringSelector:Selector) -> ([AnyObject], [String]) {
var unsortedSections = [[AnyObject]]()
//1. Create a array to hold the data for each section
for _ in self.sectionTitles {
unsortedSections.append([]) //appending an empty array
}
//2. Put each objects into a section
for item in array {
let index:Int = self.section(for: item, collationStringSelector:collationStringSelector)
unsortedSections[index].append(item)
}
//3. sorting the array of each sections
var sectionTitles = [String]()
var sections = [AnyObject]()
for index in 0 ..< unsortedSections.count { if unsortedSections[index].count > 0 {
sectionTitles.append(self.sectionTitles[index])
sections.append(self.sortedArray(from: unsortedSections[index], collationStringSelector: collationStringSelector) as AnyObject)
}
}
return (sections, sectionTitles)
}

This new partitionObjects(_:) func returns a Tuple Type like as : ([AnyObject], [String]). This tuple contain two types in it. First type of an array of AnyObject in sections and another one is an array of strings which contains custom section titles for tableview.

Now, we also need to modify the code in viewDidLoad() func.
Before that we also declare a String array variable named as sectionTitles in ViewController class for storing the section tiles for tableview.

var sectionTitles = [String]()

and replace below code with

viewDidLoad fund :
override func viewDidLoad() {
super.viewDidLoad()
let contact1 = Contact(name: "Anuska",      mob: "123434")
let contact2 = Contact(name: "Anuj Sinha", mob: "2321234")
let contact3 = Contact(name: "Maria",          mob: "343434")
let contact4 = Contact(name: "Jacob",         mob: "34454545")
let contact5 = Contact(name: "Macculam",      mob: "455656")
let contact6 = Contact(name: "Sophia",      mob: "4567890")
//add all these contacts in contacts array
self.contacts = [contact1, contact2, contact3, contact4, contact5, contact6]
//Create sections of contacts using collation object
let (arrayContacts, arrayTitles) = collation.partitionObjects(array: self.contacts, collationStringSelector: #selector(getter: Contact.name))
self.contactsWithSections = arrayContacts as! [[Contact]]
self.sectionTitles = arrayTitles
}

And also replace below code with tableview datasource and delegate

extension ViewController : UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return sectionTitles.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return contactsWithSections[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! ContactCell
let contact = contactsWithSections[indexPath.section][indexPath.row]
cell.lblName.text = contact.name
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionTitles[section]
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 44
}
}

Now Run your project and see the output screen, it looks like as below screenshot:

ScreenShot3

Above code is written in swift 3.0

Magento 2 – Multi Site product filter using REST API

$
0
0

The first question that arise on looking at the tile is: What is Multi Site to do with REST API?

The answer is simple, Magento provides multi-site support and mobile application needs the same support through REST API.

The following steps will allow a developer to develop a module which will provide product filters for multiple sites with the help of RETS API.

Step 1:

Create a custom module Company Name/ Module Name like: Demo/Simple – I am pretty sure you can make this.

Step 2:

Create file ProductListInterface.php in Demo/Simple/Api Folder

Step 3:

Place the below code in ProductListInterface.php

<?php
    namespace Demo\Simple\Api;

    interface ProductListInterface
    {
        /**
        * Get product list
        *
        * @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
        * @param string $websiteIds
        * @return \Magento\Catalog\Api\Data\ProductSearchResultsInterface
        */
        public function getProductList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria,$websiteIds);
    }

This will allow the different search criteria filter.

Step 4:

Then create di.xml in Demo/Simple/etc Folder

Step 5:

Place the below code in di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
  <preference for="Demo\Simple\Api\ProductListInterface" type="Demo\Simple\Model\ProductList" />
</config>

This will create a dependency to model.

Step 6:

Then create webapi.xml in Demo/Simple/etc Folder

Step 7:

Place the below code in webapi.xml

<?xml version="1.0"?>
<!--
/**
* Copyright 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../app/code/Magento/Webapi/etc/webapi.xsd">

<!-- Product List -->
<route url="/V1/productList" method="GET">
    <service class="Demo\Simple\Api\ProductListInterface" method="getProductList"/>
    <resources>
        <resource ref="anonymous"/>
    </resources>
</route>

</routes>

This will create routing for method.

Step 8:

Then create file ProductList.php in Demo/Simple/Model Folder

Step 9:

Place below code in ProductList.php

<?php

namespace Demo\Simple\Model;

use Demo\Simple\Api\ProductListInterface;

/**
* Defines the implementaiton class of the calculator service contract.
*/
class ProductList implements ProductListInterface
{
    protected $_objectManager = null;
      protected $_tokenkFactory;

      /**
      * @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
    */
      protected $collectionFactory;

      /**
    * @var \Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface
    */
    protected $extensionAttributesJoinProcessor;

    /**
    * @var \Magento\Catalog\Api\ProductAttributeRepositoryInterface
    */
    protected $metadataService;

    /**
    * @var \Magento\Framework\Api\SearchCriteriaBuilder
    */
  protected $searchCriteriaBuilder;

  /**
    * @var \Magento\Catalog\Api\Data\ProductSearchResultsInterfaceFactory
    */
  protected $searchResultsFactory;
   
      public function __construct(
       \Demo\Simple\Model\WsOauthTokenFactory $_tokenkFactory,
       \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $collectionFactory,
       \Magento\Catalog\Model\ResourceModel\Product $resourceModel,
       \Magento\Framework\ObjectManagerInterface $objectManager,
       \Magento\Store\Model\StoreManagerInterface $storeManager,
       \Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface $extensionAttributesJoinProcessor,
       \Magento\Catalog\Api\ProductAttributeRepositoryInterface $metadataServiceInterface,
       \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
       \Magento\Catalog\Api\Data\ProductSearchResultsInterfaceFactory $searchResultsFactory,
       \Magento\CatalogInventory\Model\StockRegistry $stock
    )
      {
          $this->_objectManager = $objectManager;
          $this->_tokenkFactory = $_tokenkFactory;
          $this->_storeManager = $storeManager;
          $this->collectionFactory = $collectionFactory;
          $this->extensionAttributesJoinProcessor = $extensionAttributesJoinProcessor;
          $this->metadataService = $metadataServiceInterface;
          $this->searchCriteriaBuilder = $searchCriteriaBuilder;
          $this->searchResultsFactory = $searchResultsFactory;
          $this->resourceModel = $resourceModel;
          $this->stockRegistryProvider = $stock;
      }


   public function getProductList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria,$websiteIds)
  {

     $webSites = explode(',', $websiteIds);

      /** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $collection */
      $collection = $this->collectionFactory->create();
      $this->extensionAttributesJoinProcessor->process($collection);

      foreach ($this->metadataService->getList($this->searchCriteriaBuilder->create())->getItems() as $metadata) {
          $collection->addAttributeToSelect($metadata->getAttributeCode());
      }
      $collection->joinAttribute('status', 'catalog_product/status', 'entity_id', null, 'inner');
      $collection->joinAttribute('visibility', 'catalog_product/visibility', 'entity_id', null, 'inner');      
      $collection->addWebsiteFilter($webSites);

      // filter for out of stock product
    $cond = array(
      '{{table}}.use_config_manage_stock = 0 AND {{table}}.manage_stock=1 AND {{table}}.is_in_stock=1',
      '{{table}}.use_config_manage_stock = 0 AND {{table}}.manage_stock=0',
     );


     $cond[] = '{{table}}.use_config_manage_stock = 1 AND {{table}}.is_in_stock=1';
       
      $collection->joinField(
          'inventory_in_stock',
          'cataloginventory_stock_item',
          'is_in_stock',
          'product_id=entity_id',
          '(' . join(') OR (', $cond) . ')'
      );

      //Add filters from root filter group to the collection
      foreach ($searchCriteria->getFilterGroups() as $group) {
          $this->addFilterGroupToCollection($group, $collection);
      }
      /** @var SortOrder $sortOrder */
      foreach ((array)$searchCriteria->getSortOrders() as $sortOrder) {
          $field = $sortOrder->getField();
          $collection->addOrder(
              $field,
              ($sortOrder->getDirection() == SortOrder::SORT_ASC) ? 'ASC' : 'DESC'
          );
      }
      $collection->setCurPage($searchCriteria->getCurrentPage());
      $collection->setPageSize($searchCriteria->getPageSize());
      $collection->load();

      $searchResult = $this->searchResultsFactory->create();
      $searchResult->setSearchCriteria($searchCriteria);
      $searchResult->setItems($collection->getItems());
      $searchResult->setTotalCount($collection->getSize());
      return $searchResult;
  }

  /**
    * Helper function that adds a FilterGroup to the collection.
    *
    * @param \Magento\Framework\Api\Search\FilterGroup $filterGroup
    * @param Collection $collection
    * @return void
    */
  protected function addFilterGroupToCollection(
      \Magento\Framework\Api\Search\FilterGroup $filterGroup,
      Collection $collection
  ) {
      $fields = [];
      $categoryFilter = [];
      foreach ($filterGroup->getFilters() as $filter) {
          $conditionType = $filter->getConditionType() ? $filter->getConditionType() : 'eq';

          if ($filter->getField() == 'category_id') {
              $categoryFilter[$conditionType][] = $filter->getValue();
              continue;
          }
          $fields[] = ['attribute' => $filter->getField(), $conditionType => $filter->getValue()];
      }

      if ($categoryFilter) {
          $collection->addCategoriesFilter($categoryFilter);
      }

      if ($fields) {
          $collection->addFieldToFilter($fields);
      }
  }
}

Step 10:

Run this REST API thru URL
http://yourdomain.com/rest/V1/productList?searchCriteria[current_page]=1&searchCriteria[page_size]=10&websiteIds=1

All Done.

Here are list of filter parameters which can be used via this:

searchCriteria[filter_groups][0][filters][0][field]=sku&
searchCriteria[filter_groups][0][filters][0][value]=simple&
searchCriteria[filter_groups][0][filters][0][condition_type]=eq&
searchCriteria[current_page]=1&
searchCriteria[page_size]=10&
websiteIds=1,2

Introduction to 3D Touch

$
0
0

Introduction

  • With iOS 9, new iPhone models add a third dimension to the user interface.
  • A user can now press your Home screen icon to immediately access functionality provided by your app.
  • Within your app, a user can now press views to see previews of additional content and gain accelerated access to features.
  • Apple’s own apps mostly use 3D Touch for getting a little preview of the next thing you want to do. So if you’re on the home screen, hard press on an icon to get a few shortcuts directly into a section of the app.
  • If you want to your app more interactive to add 3D touch in your application
  • Two major 3D touch features need to add your app.
    1. Peek and Pop
    2. Quick Actions

1. Implement Peek and Pop :

A. Storyboard -> Using Segue : (On cell Selection)

– create simple list screen as per your requirement. I already created below screen that contain tableview with simple cell
set-segue

-make sure your segue type is cell selection
cell selection

1. ListVC.swift

import UIKit

class ListVC: UIViewController {

    @IBOutlet weak var tblList: UITableView!

    var arrCompany = [Company]()
    override func viewDidLoad() {
        super.viewDidLoad()

        arrCompany.append(
            Company(name:"Apple",
                    address:"Cupertino, California, U.S.",
                    url:"https://en.wikipedia.org/wiki/Apple_Inc",
                    logo:#imageLiteral(resourceName: "apple"))
        )

        arrCompany.append(
            Company(name:"Google",
                    address:"Googleplex, Mountain View, California, U.S",
                    url:"https://en.wikipedia.org/wiki/Google",
                    logo:#imageLiteral(resourceName: "google"))
        )

        arrCompany.append(
            Company(name:"Microsoft",
                    address:"Albuquerque, New Mexico, United States",
                    url:"https://en.wikipedia.org/wiki/Microsoft",
                    logo:#imageLiteral(resourceName: "microsoft"))
        )

        arrCompany.append(
            Company(name:"Samsung",
                    address:"Seocho District, Seoul, South Korea",
                    url:"https://en.wikipedia.org/wiki/Samsung",
                    logo:#imageLiteral(resourceName: "samsung"))
        )

        arrCompany.append(
            Company(name:"Amazon",
                    address:"Seattle, Washington, U.S",
                    url:"https://en.wikipedia.org/wiki/Amazon.com",
                    logo:#imageLiteral(resourceName: "amazon"))
        )

        arrCompany.append(
            Company(name:"Facebook",
                    address:"Menlo Park, California, U.S.",
                    url:"https://en.wikipedia.org/wiki/Facebook",
                    logo:#imageLiteral(resourceName: "facebook"))
        )

        arrCompany.append(
            Company(name:"Flipkart",
                    address:"Bangalore, Karnataka, India",
                    url:"https://en.wikipedia.org/wiki/Flipkart",
                    logo:#imageLiteral(resourceName: "flipkart"))
        )

        arrCompany.append(
            Company(name:"Yahoo",
                    address:"Sunnyvale, California, U.S.",
                    url:"https://en.wikipedia.org/wiki/Yahoo!",
                    logo:#imageLiteral(resourceName: "yahoo"))
        )

    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        let cell = sender as! UITableViewCell
        let indexPath = tblList.indexPath(for: cell)!
        if segue.identifier == "segueDetails" {
            if let detailsVC = segue.destination as? DetailVC {
                detailsVC.url = arrCompany[indexPath.row].url
            }
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

extension  ListVC : UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arrCompany.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier:"ListCell")
        return cell!
    }
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if let listCell = cell as? ListCell {
            listCell.lblName.text = arrCompany[indexPath.row].name
            listCell.lblAddress.text = arrCompany[indexPath.row].address
            listCell.imgLogo.image = arrCompany[indexPath.row].logo
        }
    }
}

2. ListCell.swift

// Cell Class
class ListCell : UITableViewCell {
    @IBOutlet weak var imgLogo: UIImageView!
    @IBOutlet weak var lblName: UILabel!
    @IBOutlet weak var lblAddress: UILabel!
    override func awakeFromNib() {
        super.awakeFromNib()
    }
}

// Cell Model Class 
class Company {
    var name:String
    var address:String
    var logo : UIImage
    var url:String
    init(name:String,address:String,url:String,logo:UIImage) {
        self.name = name
        self.address = address
        self.logo = logo
        self.url = url
    }
}

3. DetailVC.swift

import UIKit

class DetailVC: UIViewController {

    var url : String?
    @IBOutlet weak var webView: UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()

        let urlReq = URL(string: url!);
        let requestObj = URLRequest(url: urlReq!)
        webView.loadRequest(requestObj)

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    func addMenuItems(menu:String ...) -> [UIPreviewActionItem] {
        var arrPreview = [UIPreviewActionItem]()
        for m in menu {
            let likeAction = UIPreviewAction(title:m, style: .default) { (action, viewController) -> Void in
                print(action.title)
            }
            arrPreview.append(likeAction)
        }
        return arrPreview
    }

	// Add Action of preview
    override var previewActionItems: [UIPreviewActionItem] {
        return self.addMenuItems(menu: "Open","Bookmark")
    }
}

peek-and-pop

2.Implement Quick Action:

– Create a UIApplicationShortcutItems array. This is where we define what the actions are, the title, subtitle, and shortcut keys, icon, dictionary. Note that you can only have a max of 4 quick actions off the icon in your app.

A. Dynamic Quick Action

type: A required string delivered to your app when the user invokes the corresponding quick action.
localizedTitle: A required string displayed to the user on the Home screen as the name of the quick action.
localizedSubtitle: An optional string that is displayed to the user on the Home screen, immediately below the corresponding title string. icon: An optional string specifying the type of an icon from the system-provided API. Full list of the icons https://developer.apple.com/reference/uikit/uiapplicationshortcuticontype. We can also set a custom icon. userInfo: An optional, app-defined dictionary.

1. AppDelegate.swift

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        UIApplication.shared.shortcutItems = getAppShortcut()
        return true
}

extension AppDelegate {

    func getAppShortcut() -> [UIApplicationShortcutItem] {

        return [ UIApplicationShortcutItem(type:"id_create",
                                    localizedTitle:"Create",
                                    localizedSubtitle:"create new item",
                                    icon:UIApplicationShortcutIcon(type: .add),
                                    userInfo:nil) ,

                 UIApplicationShortcutItem(type:"id_like",
                                           localizedTitle:"Like",
                                           localizedSubtitle:"view your favorites",
                                           icon:UIApplicationShortcutIcon(type: .favorite),
                                           userInfo:nil) ,

                UIApplicationShortcutItem(type:"id_search",
                                      localizedTitle:"Search",
                                      localizedSubtitle: nil,
                                      icon:UIApplicationShortcutIcon(type: .search),
                                      userInfo:nil) ,

                UIApplicationShortcutItem(type:"id_search1",
                                          localizedTitle:"Custom Icon",
                                          localizedSubtitle: nil,
                                          icon:UIApplicationShortcutIcon(templateImageName:"apple_logo"), // Custom Icon
                                          userInfo:nil),

        ]

    }
}

– When user tap on any quick action below method will call. You can navigate specific screen as per your requirement.

func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {

}

Quick Action Output:

quick-action

A. Static Quick Action (Info.plist)
– home screen quick actions using the UIApplicationShortcutItems array in the app Info.plist file

1. Info.plist :
plist-screenshot

– add this key into you info.plist file

<key>UIApplicationShortcutItems</key>
<array>
<dict>
    <key>UIApplicationShortcutItemIconType</key>
    <string>UIApplicationShortcutIconTypeSearch</string>
    <key>UIApplicationShortcutItemSubtitle</key>
    <string>shortcutSubtitle1</string>
    <key>UIApplicationShortcutItemTitle</key>
    <string>shortcutTitle1</string>
    <key>UIApplicationShortcutItemType</key>
    <string>$(PRODUCT_BUNDLE_IDENTIFIER).First</string>
    <key>UIApplicationShortcutItemUserInfo</key>
        <dict>
            <key>firstShorcutKey1</key>
            <string>firstShortcutKeyValue1</string>
        </dict>
</dict>
</array>

PayUMoney Payment Integration with IPN in Codeigniter

$
0
0

Overview

Payment gateway offers the desired and vital link between the online seller (merchant), its customer, the customer’s online payment instrument provider and the bank account of the online merchant.

  • First create merchant account in PayUMoney.
  • The PayU Redirect Payment Page (RPP) allows merchants to integrate into PayU by redirecting their consumers to PayU’s hosted payment page.
  • This is accomplished by using a combination of server side API calls and HTTPS redirects.
  • The setTransaction API call is used to setup/initiate transactions between the merchant and PayU using server to server requests.
  • Now first do setTransaction API call into your controller.

error_reporting(E_ALL);
			ini_set('display_errors', 1);
			ob_start();

			//-------------------------------------------------------------------
			//-------------------------------------------------------------------
			//-------
			//-------      Configs comes here
			//-------
			//-------------------------------------------------------------------
			//-------------------------------------------------------------------
			$baseUrl = 'https://staging.payu.co.za'; // testing environment URL
			// $baseUrl = 'https://secure.payu.co.za'; //production environment URL

			$soapWdslUrl = $baseUrl . '/service/PayUAPI?wsdl';
			$payuRppUrl = $baseUrl . '/rpp.do?PayUReference=';
			$apiVersion = 'ONE_ZERO';

			//set value != 1 if you dont want to auto redirect topayment page
			$doAutoRedirectToPaymentPage = 1;

			/*
			Store config details
 			*/
			$safeKey = '{CE62CE80-0EFD-4035-87C1-8824C5C46E7F}'; // safe key provided in merchant account
			$soapUsername = '100032'; // SOAP username provided in merchant account
			$soapPassword = 'PypWWegU'; // SOAP password provided in merchant account

			try {

				// 1. Building the Soap array  of data to send
				$setTransactionArray = array();
				$setTransactionArray['Api'] = $apiVersion;
				$setTransactionArray['Safekey'] = $safeKey;
				$setTransactionArray['TransactionType'] = 'PAYMENT';

				$setTransactionArray['AdditionalInformation']['merchantReference'] = 203269; //provided in merchant account
				$setTransactionArray['AdditionalInformation']['cancelUrl'] = 'http://your-cancel-url-comes-here';
				$setTransactionArray['AdditionalInformation']['returnUrl'] = 'http://your-return-url-comes-here';
				$setTransactionArray['AdditionalInformation']['notificationUrl'] = 'http://your-notification-url-comes-here';
				$setTransactionArray['AdditionalInformation']['supportedPaymentMethods'] = 'CREDITCARD';

				$setTransactionArray['Basket']['description'] = "Load Funds";
				$setTransactionArray['Basket']['amountInCents'] = 1000 // amount in cents
				$setTransactionArray['Basket']['currencyCode'] = 'ZAR';

				$setTransactionArray['Customer']['email'] = “john@doe.com”;
				$setTransactionArray['Customer']['firstName'] = 'John';
				$setTransactionArray['Customer']['lastName'] = 'Doe';
				$setTransactionArray['Customer']['mobile'] = '0211234567';
				$setTransactionArray['Customer']['regionalId'] = '1234512345122';
				$setTransactionArray['Customer']['countryCode'] = '27';

				// 2. Creating a XML header for sending in the soap heaeder (creating it raw a.k.a xml mode)
				$headerXml = '<wsse:Security SOAP-ENV:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">';
				$headerXml .= '<wsse:UsernameToken wsu:Id="UsernameToken-9" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">';
				$headerXml .= '<wsse:Username>' . $soapUsername . '</wsse:Username>';
				$headerXml .= '<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">' . $soapPassword . '</wsse:Password>';
				$headerXml .= '</wsse:UsernameToken>';
				$headerXml .= '</wsse:Security>';
				$headerbody = new SoapVar($headerXml, XSD_ANYXML, null, null, null);

				// 3. Create Soap Header.
				$ns = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'; //Namespace of the WS.
				$header = new SOAPHeader($ns, 'Security', $headerbody, true);

				// 4. Make new instance of the PHP Soap client
				$soap_client = new SoapClient($soapWdslUrl, array("trace" => 1, "exception" => 0));

				// 5. Set the Headers of soap client.
				$soap_client->__setSoapHeaders($header);

				// 6. Do the setTransaction soap call to PayU
				$soapCallResult = $soap_client->setTransaction($setTransactionArray);

				// 7. Decode the Soap Call Result
				$returnData = json_decode(json_encode($soapCallResult), true);
				print "<br />-----------------------------------------------<br />\r\n";
				print "Return data decoded:<br />\r\n";
				print "-----------------------------------------------<br />\r\n";
				print "<pre>";
				var_dump($returnData);
				print "</pre>";

				if (isset($doAutoRedirectToPaymentPage) && ($doAutoRedirectToPaymentPage == 1)) {

					if ((isset($returnData['return']['successful']) && ($returnData['return']['successful'] === true) && isset($returnData['return']['payUReference']))) {
						// do some database insertion if you want to do
						// Redirecting to payment page
						header('Location: ' . $payuRppUrl . $returnData['return']['payUReference']);
						die();
					}
				}
			} catch (Exception $e) {
				var_dump($e);
			}

			//-------------------------------------------------------------------
			//-------------------------------------------------------------------
			//-------
			//-------      Checking response
			//-------
			//-------------------------------------------------------------------
			//-------------------------------------------------------------------
			if (is_object($soap_client)) {

				print "<br />-----------------------------------------------<br />\r\n";
				print "Request in XML:<br />\r\n";
				print "-----------------------------------------------<br />\r\n";
				echo str_replace('&gt;&lt;', '&gt;<br />&lt;', htmlspecialchars($soap_client->__getLastRequest(), ENT_QUOTES));
				print "\r\n<br />";
				print "-----------------------------------------------<br />\r\n";
				print "Response in XML:<br />\r\n";
				print "-----------------------------------------------<br />\r\n";
				echo str_replace('&gt;&lt;', '&gt;<br />&lt;', htmlspecialchars($soap_client->__getLastResponse(), ENT_QUOTES));
				// echo "test";exit;
			}
			die();

  • After completion this, your page redirect to “returnURL” .
  • Internally it also fire IPN (Instant Payment Notification). The Instant Payment Notification (IPN) is an asynchronous notification mechanism where PayU sends transaction results/information to a specified URL without any dependency on a customer’s browser.
  • Notifications are sent in XML format using POST method.
  • In the case of approval the IPN will fire after the payment has been attempted and will return that result.

IPN called under following conditions:

  1. When a payment on the PayU redirect either fails or succeeds.
  2. When a user session times out on the PayU redirect with no chance for the user to finish payment.
  3. When a transaction, pending review for fraud, is either approved or rejected by case managers.

In your notification page write below code

$postdata = file_get_contents("php://input"); // get post data
		$xml = json_decode(json_encode(simplexml_load_string($postdata)), true); // convert it into array

		$paureference = $xml['PayUReference']; // unique payU reference
		$transaction = $xml['Secure3D']['lkpTransactionId']; // unique transaction id

		if ($xml['TransactionState'] == 'SUCCESSFUL' && isset($xml['Secure3D']['lkpTransactionId'])) {
			// do something if transaction succeed.
		} else if ($xml['TransactionState'] == 'FAILED') {
			// do something if transaction fails.
		} else if (empty($xml['Secure3D'] && $xml['Secure3D'] == '')) {
			//do something if transaction succeed but Issuer/Cardholder not participated.
		}

Bravo!!! Now you can collect payment from your customers.


White Space Troubling During use of Display Inline Elements

$
0
0

Many times, we face spacing problems during HTML development with display: inline-block.

So, we will try to resolve this problem with many ways.

Example:

HTML:

<ul class="inline-list">
<li><a href="element1.html">element 1</a></li>
<li><a href="element2.html">element 2</a></li>
<li><a href="element3.html">element 3</a></li>
</ul>

CSS:

ul.inline-list li 
{
display: inline-block;
padding: 8px;
background: #000;
}
ul.inline-list li a
{
text-decoration: none;
}

So how we control the spacing between elements.
whitespace-screen1

whitespace-screen2

Below are the mentioned solutions for this problem.

Solution 1: Apply font-size: 0px to the parent.

One of the most simple solutions for that is removing extra whitespace by applying font-size to 0 on the parent of inline-block elements.
By the applying font-size 0 to parent, need to mention child font-size different.

below are the example for that,

/* Parent*/
ul.inline-list 
{
   font-size: 0;
}
/*Child*/
ul.inline-list li
{
   font-size: 16px;
}

Solution 2: Minimize the HTML

Remove space between HTML elements by two method,

2.1. Drop Close Angle or Drop element Closing angle with the content

<ul class="inline-list">
<li><a href="element1.html">element 1</a></li
><li><a href="element2.html">element 2</a></li
><li><a href="element3.html">element 3</a></li>
</ul>

Or

<ul class="inline-list">
<li><a href="element1.html">element 1</a>
</li><li><a href="element2.html">element 2</a>
</li><li><a href="element3.html">element 3</a></li>
</ul>

2.2. Make all Element in Single Row

<ul class="inline-list">
<li><a href="element1.html">element 1</a></li><li><a href="element2.html">element 2</a></li><li><a href="element3.html">element 3</a></li>
</ul>

Solution 3: HTML Comments or Avoid Closing Tag for that

3.1 Simply apply HTML Comments between elements, start of the comment with first element and half of the close comment with second element.

<ul class="inline-list">
<li><a href="element1.html">element 1</a></li><!--
--><li><a href="element2.html">element 2</a></li><!--
--><li><a href="element3.html">element 3</a></li>
</ul>

Or

3.2 Avoid closing tag of each element

but I think this one is not a good way with the w3c markup validation.

<ul class="inline-list">
<li><a href="element1.html">element 1</a>
<li><a href="element2.html">element 2</a>
<li><a href="element3.html">element 3</a>
</ul>

Solution 4: Oppose Margin with the elements

First, remove display inline-block and another but undesirable solutions for that is to apply margin-left in negative value like margin-left value is -4px.

/*Child*/
ul.inline-list li
{
   /*Remove display: inline-block;*/
  margin-left: -4px;
}

It will affect all elements so you need to reset first child for that. li:first-child to reset margin as a zero value.

/*For Reset First Element Margin*/
ul.inline-list li:first-child
{
   /*Remove display: inline-block;*/
  margin-left: 0px;
}

Solution 5: Applying Flex

In case of acceptable browser support Use Flex Box for that, it is the best way to adjust this kind of spacing issue. Just apply display flex to parent, no need to apply anything to the child.

Below are the examples for that,

/* Parent*/
ul.inline-list 
{
   display: flex; display: -webkit-flex;
}

Solution 6: Applying Float

In place of display: inline-block; try to apply float between elements so this is a good way to adjust elements’ margin and padding.

/*Child*/
ul.inline-list li
{
   /*Remove display: inline-block;*/
  float: left;
}

New Features in PHP 7

$
0
0

PHP 7 is kind of super major release of PHP programming language and is considered to be a revolution in the way web applications can be developed and delivered. PHP 7 release is considered to be the most important change for PHP after the release of PHP 5.

Performance & Speed

The most easily recognizable advantage of the new PHPNG engine is the significant performance improvement. The development team of PHPNG refactored (Improved by reorganising its internal structure without altering its external behaviour) the Zend Engine, and optimized memory usage in a remarkable way. The results? You can see the performance benchmarks provided by the Zend Performance Team below. Using PHP 7 executes your code faster as well as you will also need only fewer servers to serve the same amount of users.

framework

WordPress

New Operators

Spaceship Operator

PHP 7 also brings us some new operators. The first one we’re going to explore is the spaceship operator. The name itself has an attraction, who doesn’t want to use it? The spaceship operator, or Combined Comparison Operator, is good addition to the language, complementing the greater-than and less-than operators.

php7

Example:

$myCompare = 2 <=> 1
2 < 1? will return -1
2 = 1? will return 0
2 > 1? will return 1

The spaceship operator is put together(combined with) using three individual operators, less than, equal, and greater than. Essentially what it does is check the each operator individually. First we have less than, If the value on the left side is less than the value on the right side, the spaceship operator will return -1. If not, it will move on to test if the value on the left is EQUAL to the value on the right(both equal). If so, it will return 0. If not then finally it will move on to the final test. If the value on the left is GREATER THAN the value on the right. Which, if the other 2 haven’t passed, this one must be true. And it will return 1.

Null Coalesce Operator

The Null Coalescing operator is denoted with two question marks ( ?? ). You can use it when you want to check if something exists and you need to return a default value, in case it doesn’t. The coalesce operator returns the result of its first operand if it exists and is not null, and the second operand in any other cases.

Example:

<?php
// $varA is not set
$varB = 20;

echo $varA ?? 5; // outputs 5
echo $varA ?? $varB ?? 8; // outputs 20    
?>

Type Declarations

It has simply meaning, giving type to variable instead of allowing PHP to set automatically.

Scalar type declarations

Scalar type declaration has two options −

  • coercive – coercive is default mode and hence there is no need be specified.
  • strict – strict mode has to explicitly hinted.

The above modes do allow following types for function parameters −

  • int
  • float
  • bool
  • string
  • interfaces
  • array
  • callable
Coercive Mode Example:

<?php
   // Coercive mode
   function mySum(int ...$ints) {
      return array_of_sum($ints);
   }
   print(mySum(1, '2', 3.2));
?>

Output: 6

Strict Mode Example:

<?php
   // Strict mode
   declare(strict_types=1);
   function mySum(int ...$ints) {
      return array_of_sum($ints);
   }
   print(mySum(2, '3', 4.1));
?>

Output: Fatal error: Uncaught TypeError: Argument 2 passed to mySum() must be of the type integer, string given.

Return type

Return type declaration specifies the type of value that a function should return. Following types for return types can be declared.

  • int
  • float
  • bool
  • string
  • interfaces
  • array
  • Callable
Valid Return Type Example:

<?php
   declare(strict_types = 1);
   function returnMyIntValue(int $myValue): int {
      return $myValue;
   }
   print(returnMyIntValue(8));
?>

Output: 5

Invalid Return Type Example:

<?php
   declare(strict_types = 1);
   function returnMyIntValue(int $myValue): int {
      return $myValue + 1.0;
   }
   print(returnMyIntValue(5));
?>

Output: Fatal error: Uncaught TypeError: Return value of returnMyIntValue() must be of the type integer, float returned.

CSPRNG

CSPRNG stands for ‘Cryptographically Secure Pseudo-Random Number Generator’. In cryptography, we require random numbers, in the case of salts, nonce, key generation, one-time pads in certain signature schemes, etc. Hence, CSPRNG is named after this phenomenon.

PHP 7 has two new functions, which are used to generate cryptographically secure pseudo-random integers and strings in a cross-platform method. These functions are as follows.

random_bytes ()

The use of this function is to generate an arbitrary-length string of cryptographically secure pseudo-random bytes. These bytes has only cryptographic use like when we generate keys or initialize vectors as discussed before. Following is the syntax for this function.

Syntax

string random_bytes ( int $myLength ); // where $myLength = number of length

  • Parameter – The function accepts the length of the string as an input parameter. It is of integer type and given in terms of number of bytes.
  • Return Value – The function returns a string value which is cryptographically secure random bytes.
  • Errors/Exceptions – Exceptions or errors will be thrown by the function in the following scenarios.
  • If no source of randomness is found then an exception will be thrown.
  • A TypeError will be thrown when input parameters are invalid.
  • An error will be thrown when input parameter is passed which has an invalid length.
Example:

In the below example, we are going to generate a random string of length 10 bytes.

<?php
$myBytes = random_bytes(10);
print(bin2hex($myBytes));
?>

Output: 2a58cdaf2117aee1f00a

random_int ()

This function is used to generate cryptographically secure pseudo-random integers. These integers are only used when the unbiased results are critical. Following is the syntax for this function.

Syntax

int random_int ( int $min , int $max );

  • Parameters – The function accepts two input parameters ‘$min’ and ‘$max’. Both of these parameters accept integer values.
  • As the name suggests ‘$min’ is the lowest value that is to be returned which could be either PHP_INT_MIN or higher.
  • On the other hand ‘$max’ is the highest value that to be returned which could be, either less than or equal to PHP_INT_MAX.
  • Return Value – The function returns an integer value which is a cryptographically secure random integer. This integer value will always be between the min and max range that were given as input parameters.
  • Errors/Exceptions – Exception or error will be thrown by the function in the following scenarios.
  • If no source of randomness is found then an exception will be thrown.
  • A TypeError will be thrown when input parameters are invalid.
  • An error will be thrown when the value of ‘$max’ is given less than the value of ‘$min’ as input parameters.
Example:

<?php
print(random_int(50, 1000));
print("");
print(random_int(-1000, 0));
?>

Output: 
116
-647

Anonymous Classes

Anonymous classes can now be defined using new class. Anonymous class can be used in place of a full class definition.

<?php
   interface MyLogger {
      public function myLog(string $msg);
   }
   class MyApplication {
      private $myLogger;
      public function getMyLogger(): MyLogger {
         return $this->myLogger;
      }
      public function setMyLogger(MyLogger $myLogger) {
         $this->myLogger = $myLogger;
      }  
   }
   $myApp = new MyApplication;
   $myApp->setMyLogger(new class implements MyLogger {
      public function myLog(string $myMsg) {
         print($myMsg);
      }
   });
   $myApp->getMyLogger()->myLog("Anonymous Classes Example");
?>

Output: Anonymous Classes Example

New Features in PHP 7

$
0
0

PHP 7 is kind of super major release of PHP programming language and is considered to be a revolution in the way web applications can be developed and delivered. PHP 7 release is considered to be the most important change for PHP after the release of PHP 5.

Performance & Speed

The most easily recognizable advantage of the new PHPNG engine is the significant performance improvement. The development team of PHPNG refactored (Improved by reorganising its internal structure without altering its external behaviour) the Zend Engine, and optimized memory usage in a remarkable way. The results? You can see the performance benchmarks provided by the Zend Performance Team below. Using PHP 7 executes your code faster as well as you will also need only fewer servers to serve the same amount of users.

framework

WordPress

New Operators

Spaceship Operator

PHP 7 also brings us some new operators. The first one we’re going to explore is the spaceship operator. The name itself has an attraction, who doesn’t want to use it? The spaceship operator, or Combined Comparison Operator, is good addition to the language, complementing the greater-than and less-than operators.

php7

Example:

$myCompare = 2 <=> 1
2 < 1? will return -1
2 = 1? will return 0
2 > 1? will return 1

The spaceship operator is put together(combined with) using three individual operators, less than, equal, and greater than. Essentially what it does is check the each operator individually. First we have less than, If the value on the left side is less than the value on the right side, the spaceship operator will return -1. If not, it will move on to test if the value on the left is EQUAL to the value on the right(both equal). If so, it will return 0. If not then finally it will move on to the final test. If the value on the left is GREATER THAN the value on the right. Which, if the other 2 haven’t passed, this one must be true. And it will return 1.

Null Coalesce Operator

The Null Coalescing operator is denoted with two question marks ( ?? ). You can use it when you want to check if something exists and you need to return a default value, in case it doesn’t. The coalesce operator returns the result of its first operand if it exists and is not null, and the second operand in any other cases.

Example:

<?php
// $varA is not set
$varB = 20;

echo $varA ?? 5; // outputs 5
echo $varA ?? $varB ?? 8; // outputs 20    
?>

Type Declarations

It has simply meaning, giving type to variable instead of allowing PHP to set automatically.

Scalar type declarations

Scalar type declaration has two options −

  • coercive – coercive is default mode and hence there is no need be specified.
  • strict – strict mode has to explicitly hinted.

The above modes do allow following types for function parameters −

  • int
  • float
  • bool
  • string
  • interfaces
  • array
  • callable
Coercive Mode Example:

<?php
   // Coercive mode
   function mySum(int ...$ints) {
      return array_of_sum($ints);
   }
   print(mySum(1, '2', 3.2));
?>

Output: 6

Strict Mode Example:

<?php
   // Strict mode
   declare(strict_types=1);
   function mySum(int ...$ints) {
      return array_of_sum($ints);
   }
   print(mySum(2, '3', 4.1));
?>

Output: Fatal error: Uncaught TypeError: Argument 2 passed to mySum() must be of the type integer, string given.

Return type

Return type declaration specifies the type of value that a function should return. Following types for return types can be declared.

  • int
  • float
  • bool
  • string
  • interfaces
  • array
  • Callable
Valid Return Type Example:

<?php
   declare(strict_types = 1);
   function returnMyIntValue(int $myValue): int {
      return $myValue;
   }
   print(returnMyIntValue(8));
?>

Output: 5

Invalid Return Type Example:

<?php
   declare(strict_types = 1);
   function returnMyIntValue(int $myValue): int {
      return $myValue + 1.0;
   }
   print(returnMyIntValue(5));
?>

Output: Fatal error: Uncaught TypeError: Return value of returnMyIntValue() must be of the type integer, float returned.

CSPRNG

CSPRNG stands for ‘Cryptographically Secure Pseudo-Random Number Generator’. In cryptography, we require random numbers, in the case of salts, nonce, key generation, one-time pads in certain signature schemes, etc. Hence, CSPRNG is named after this phenomenon.

PHP 7 has two new functions, which are used to generate cryptographically secure pseudo-random integers and strings in a cross-platform method. These functions are as follows.

random_bytes ()

The use of this function is to generate an arbitrary-length string of cryptographically secure pseudo-random bytes. These bytes has only cryptographic use like when we generate keys or initialize vectors as discussed before. Following is the syntax for this function.

Syntax

string random_bytes ( int $myLength ); // where $myLength = number of length

  • Parameter – The function accepts the length of the string as an input parameter. It is of integer type and given in terms of number of bytes.
  • Return Value – The function returns a string value which is cryptographically secure random bytes.
  • Errors/Exceptions – Exceptions or errors will be thrown by the function in the following scenarios.
  • If no source of randomness is found then an exception will be thrown.
  • A TypeError will be thrown when input parameters are invalid.
  • An error will be thrown when input parameter is passed which has an invalid length.
Example:

In the below example, we are going to generate a random string of length 10 bytes.

<?php
$myBytes = random_bytes(10);
print(bin2hex($myBytes));
?>

Output: 2a58cdaf2117aee1f00a

random_int ()

This function is used to generate cryptographically secure pseudo-random integers. These integers are only used when the unbiased results are critical. Following is the syntax for this function.

Syntax

int random_int ( int $min , int $max );

  • Parameters – The function accepts two input parameters ‘$min’ and ‘$max’. Both of these parameters accept integer values.
  • As the name suggests ‘$min’ is the lowest value that is to be returned which could be either PHP_INT_MIN or higher.
  • On the other hand ‘$max’ is the highest value that to be returned which could be, either less than or equal to PHP_INT_MAX.
  • Return Value – The function returns an integer value which is a cryptographically secure random integer. This integer value will always be between the min and max range that were given as input parameters.
  • Errors/Exceptions – Exception or error will be thrown by the function in the following scenarios.
  • If no source of randomness is found then an exception will be thrown.
  • A TypeError will be thrown when input parameters are invalid.
  • An error will be thrown when the value of ‘$max’ is given less than the value of ‘$min’ as input parameters.
Example:

<?php
print(random_int(50, 1000));
print("");
print(random_int(-1000, 0));
?>

Output: 
116
-647

Anonymous Classes

Anonymous classes can now be defined using new class. Anonymous class can be used in place of a full class definition.

<?php
   interface MyLogger {
      public function myLog(string $msg);
   }
   class MyApplication {
      private $myLogger;
      public function getMyLogger(): MyLogger {
         return $this->myLogger;
      }
      public function setMyLogger(MyLogger $myLogger) {
         $this->myLogger = $myLogger;
      }  
   }
   $myApp = new MyApplication;
   $myApp->setMyLogger(new class implements MyLogger {
      public function myLog(string $myMsg) {
         print($myMsg);
      }
   });
   $myApp->getMyLogger()->myLog("Anonymous Classes Example");
?>

Output: Anonymous Classes Example

Layer in swift 3.0

$
0
0

Overview

Layer is visual attributes you can set background color,border & show etc.. Almost UI control have one layer CALayer by using that you can use to provide border , round corner etc..

There are many layers in iOS but we are looking for few important layers here.

Topic 1: CAGradientLayer

Generally, if we have UI with gradient effect for 2 colours, we use image in our project which increases our app bundle size bit, so we have gradient layer to do it easily.

Just few lines of code and it’s done, check below code:

let layer = CAGradientLayer()
layer.frame = CGRect(x: 64, y: 64, width: 160, height: 160)
layer.colors = [UIColor.red.cgColor,UIColor.blue.cgColor,UIColor.yellow.cgColor ,UIColor.black.cgColor]
layer.locations = [0,0.3,0.5,0.7,1]
        layer.startPoint = CGPoint(x: 0, y: 0)
layer.endPoint = CGPoint(x: 1, y: 1)

view.layer.addSublayer(layer)

Here First we will make instance of layer then set frame.

colours: It’s an array property to set multiple colours

locations: Locations property is used to define area of colour between 0 to 1 range.

startPoint,endPoint: We have to provide directions of gradient, start & end position Default value is 0.5,0.5

screen1

Topic 2: CAShapeLayer

CAShapeLayer is used to draw custom UI using BezierPath object.

Using UIBezierPath we draw custom shape like polygon, triangle etc..

Here we make rounded layer object.

let layer = CAShapeLayer()
layer.path = UIBezierPath(roundedRect: CGRect(x: 64, y: 230, width: 160, height: 160), cornerRadius: 50).cgPath
layer.fillColor = UIColor.red.cgColor
view.layer.addSublayer(layer)

screen2

UIBezierPath

Let us create triangle path & apply to view.
First we create custom view & override draw method.

let myBezier = UIBezierPath()
myBezier.move(to: CGPoint(x: 0, y: 0))
myBezier.addLine(to: CGPoint(x: 100, y: 0))
myBezier.addLine(to: CGPoint(x: 50, y: 100))
myBezier.close()
UIColor.blue.setStroke()
let color = UIColor(patternImage: image)
color.setFill()

myBezier.stroke()
myBezier.fill()

Here we are using move & addLine function we draw the path.

  • we will also fill pattern image in layer
  • fill() – fill the color inside triangle
  • strock() – Draw border on triangle

screen3

Topic 3: ReplicateLayer

Using RelicateLayer , We can create number of copies of sub-layers, each copy potentially having geometric, temporal, and color transformations applied to it.

Let’s create simple square relicatelayer see below code.

let replicatorLayer = CAReplicatorLayer()
let redSquare = CALayer()
redSquare.backgroundColor = UIColor.green.cgColor
redSquare.frame = CGRect(x: 5, y: 250, width: 50, height: 50)
let instanceCount = 5
replicatorLayer.instanceCount = instanceCount
replicatorLayer.instanceTransform = CATransform3DMakeTranslation(55, 0, 0)
let offsetStep = -1 / Float(instanceCount)
replicatorLayer.instanceBlueOffset = offsetStep
replicatorLayer.instanceGreenOffset = offsetStep
replicatorLayer.addSublayer(redSquare)
view.layer.addSublayer(replicatorLayer)

Here we first create instance of delicatelayer then create CALayer with green color & provide frame.

instanceCount

This property indicates number of copies you want to create.

instanceTransform

This property indicates the translation of each layer related to position

instanceGreenOffset,instanceGreenOffset

This is float value to create color (R,G,B) object

screen4

What is SASS & How we use it

$
0
0

What is SASS

SASS (Syntactically Awesome StyleSheets) is an extension of CSS. SASS allows you to usefeatures like nested rules, variables, mixins, selector inheritance, and more.

It also helps to keep everything very organized and allows you to create stylesheets faster. Now we see how to install SASS.

Install SASS

Before we can compose SASS we need to install it. SASS is built upon Ruby. If you are working on a Mac, you have already installed Ruby. If you may install Ruby in Windows, use this Ruby Installer.

After the installation of SASS is completed, you can go to Terminal (on a Mac) or in Command Prompt (on Windows) then type the following command line in it:

Mac

sudo gem install sass

Windows

gem install sass

SASS Applications

However, if you dislike working through Terminal or Command Prompt, you can use some applications for SASS. Scout is free to use it is built on Adobe Air so it can be run on all OS (Windows, Max and Linux). Some paid applications like Compass.app, Fire.app, Codekit are also available for SASS.

SASS Basic

CSS on its own can be fun, but stylesheets are getting larger, more difficult, and harder to maintain. This is where a preprocessor can help. SASS lets you use features that do not exist in CSS yet like variables, nesting, mixins, inheritance and other nifty goodies that make writing CSS fun again.

Variables

In CSS write color or font-stack every time when you put new CSS. Each and every time you have to search for your color (hexadecimal code) or font-stack that’s very time consuming.

SASS provides variables as a way to store information that you want to use every time throughout your stylesheet. You can store color value and also easy to remember long font stack. The way you declare a variable is with a dollar sign $ followed by the name.

$primary-font: Helvetica, sans-serif;
$primary-color: #000;

body { font: $primary-font; color: $primary-color; }

When the SASS is processed, it takes the variables we define for the $primary-font and $primary-color and outputs in normal CSS with our variable values placed in the CSS. This can be most powerful when working with brand colors and keeping them consistent throughout the site.

body { font: Helvetica, sans-serif; color: #000; }

Nesting

With nesting you make your CSS easier to read, extend, and maintain. For some situations its work  but for designing CSS is very lengthy, nesting your CSS is almost always a terrible idea.

nav {

     ul {
        margin: 0;
        padding: 0;
        list-style: none;
    }

     li {display: inline-block;}

     a {
         display: block;
        padding: 5px 10px;
        text-decoration: none;
     }
}

Now you can see that the ul, li, and a selectors are nested inside the nav selector. This is a great way to manage your CSS and make it more readable. When you generate the CSS you’ll get something like this:

nav ul {
     margin: 0;
     padding: 0;
     list-style: none;
}

nav li {
     display: inline-block;
}

nav a {
     display: block;
     padding: 5px 10px;
     text-decoration: none;
}

Mixing

SASS mixins are blocks of code that you define once and can then re-use anywhere, if you are aware with any programming language you can think of them as functions. A mixin can take one or more parameters and make calls to functions to in the end output CSS, and they are very useful when you want really clean and DRY code.

@mixin linx ($link, $visit, $hover, $active) {
      a {
        color: $link;
        &:visited {
          color: $visit;
        }
        &:hover {
          color: $hover;   
        }
        &:active {
          color: $active;
        }
    }
}
@include linx(white, blue, green, red);

To create a mixin you use the @mixin directive and give it a name. We’ve named our mixin linx. We’re also using the variables $link, $visit, $hover, $active inside the parentheses so we can pass in a linx of whatever we want. After you create your mixin, you can use it CSS declaration before write @include followed by the name of the mixin. When your CSS is generated it’ll look like this:

a:link {color: white;}
a:visited {color: blue;}
a:hover {color: green;}
a:active {color: red;}

Import

Now you might think that CSS has also use of @import, it is not that cool” and you would be right but the CSS and SASS versions are different in a significant way. In normal CSS @import add or import other style sheets but it does this by making another HTTP request, something we usually want to avoid. For this particular reason you may not have even used @import before. On the other hand SASS is a preprocessor (emphasis on the pre) that will pull in that file before it compiles CSS.

The result is one CSS page is handled by one HTTP request. Its means that you can break your css into smaller one and more maintainable bit while still only serving one page to the browser.

Let’s say you have a couple of SASS files, _reset.scss and base.scss. Now you import _reset.scss into base.scss.

//_reset.scss
html, body, ul, ol {
    margin: 0;
    padding: 0;
}

//_base.scss
@import ‘reset’;

body {
    font: 100% Arial, sans-serif;
    background-color: #f9f9f9;
}

Notice we’re using @import ‘reset’; in the base.scss file. When you import a file you do not need to add the file extension .scss. SASS is smart and will figure it out for you. When you generate the CSS you’ll get:

html, body, ul, ol {
    margin: 0;
    padding: 0;
}
body {
    font: 100% Arial, sans-serif;
    background-color: #f9f9f9;
}

Extend

These tools been great but I’ve saved the best for last. Extend is one of the most useful features that allows us to share a set of CSS properties from one selector to another. The pair of buttons, like an accept button and decline button on a modal window. Since they are both buttons they will probably share most of the same styling but the decline button with red background to make it differ. With use of SASS we write the default styles for all buttons then “extend” these styles to the decline button where we would add the red background.

.button {
    background: rgba($color, .8);
    color: lighten($color, 65%);
    border: 1px solid darken($color, 5%);
    padding: 1em;
    display: block;
    max-width: 200px;
}
.button-decline {
    @extend .button;
    background: red;
}

What the above code does is allows you to take the CSS properties in .button and apply them to .button-decline. The magic happens with the generated CSS and this helps you to consume your time to write multiple class names on HTML elements. This is what it looks like:

.button, .button-decline {
    background: rgba(51, 51, 51, 0.8);
    color: #d9d9d9;
    border: 1px solid #262626;
    padding: 1em;
    display: block;
    max-width: 200px;
}
.button-decline {
    background: red;
}

Give SASS a chance for your next website its very usefulness and time consuming for your project.

PHP: die() Vs exit() – It has no difference but a difference

$
0
0

Overview

We are all at starting phase of learning, PHP has a BIG question on what is the difference between die() and exit(). The excitement of preparing a code with both statements, searching for answers and getting to a result is heart whelming.

It’s a general tendency to use exit() for testing/stopping execution and die() for checking database connection/operations.

Let’s compare it both… A step by step explanation to die Vs exit

PHP Language Constructs comparison “exit” Vs “die”:

NOTE: Built-in Functions are slower compared to Language Constructs, Language Constructs does not need parenthesis

Example 1:

Test exit:

<?php
    for($count=0;$count<10;$count++) {
        if($count==2)
            exit(); // stops execution from this.
    }
?>

Test die:

<?php
    for($count=0;$count<10;$count++) {
        if($count==2)
            die(); // stops execution from this - (same as above)
    }
?>

Example 2:

Test exit:

<?php
    $dblink = mysql_connect('host.domain.com', 'mysql_user_one', 'mysql_password_for_user_one');
    if (!$link) {
        exit('Could not connect: ' . mysql_error()); // stops execution printing "Could not connect: MYSQL_ERROR"
    }
    echo 'Connected successfully';
    mysql_close($link);
?>

Test die:

<?php
    $dblink = mysql_connect('host.domain.com', 'mysql_user_one', 'mysql_password_for_user_one');
    if (!$link) {
        die('Could not connect: ' . mysql_error()); // stops execution printing "Could not connect: MYSQL_ERROR"  - (same as above)
    }
    echo 'Connected successfully';
    mysql_close($link);
?>

As mysql_connect is deprecated from PHP 5.5 and is obsolete on PHP 7 you can try with mysqli_connect. Both (exit and die) can be used without parenthesis.

Example 3:

Test exit:

<?php
    for($count=0;$count<10;$count++) {
        if($count==2)
            exit; // stops execution from this.
    }
?>

Test die:

<?php
    for($count=0;$count<10;$count++) {
        if($count==2)
            die; // stops execution from this - (same as above)
    }
?>

The conclusion comes that both works SAME – there is no functional level differences with both.

If you check on php.net for die and exit definitions it’s mentioned:

exit — Output a message and terminate the current script

die — Equivalent to exit

But still there is a little or no difference – server need to read 4 characters for exit whereas server need to read 3 characters for die. For micro time difference die will execute faster then exit.

These are called “Aliases” – different name but same functional execution.

There are many more function aliases – you can get a grip from http://php.net/manual/en/aliases.php.

I insist to use die instead of exit on regular basis. Ultimately it’s on developer to choose on what to use, there is lot more than “Hello World” to explore.

WordPress Child Theme: How to make?

$
0
0

Introduction of WordPress child theme

WordPress child theme we create using parent theme. If we require any customisation on theme as per our requirement, we create a child theme.

How to create a child theme?

First step to install a WordPress. create a database for the project. After that give meaning full name of the project.

image00

After that we can choose any theme for our project. Put wp-content under theme folder. Now set the theme for our project. Once all these steps are completed, we move further for our main part that is a child theme.

image03

Now we create a child theme for that we will follow some steps. We copy the parent theme after that give a name for child theme here project name is intraday so child theme is same and related to the parent theme so give a meaningful name for it. I have given the name as cuda-child.

image04

Now in a child theme which file we required only that file we will put on child theme. Only three files we will need for child theme folder.

  1. style.css
  2. functions.php
  3. screenshot.png

image05

If we need to change any structure and we need for customisation of this project so we can easily do that using a child theme. If we required to change n header or footer file, we can
copy that file and pass to a child theme and now what ever changes is required in header or footer part then we make changes on child theme only no need to change parent theme.

We see here on screenshot as:

  1. page-fullwidth.php
  2. header.php
  3. footer.php

image01

We create a child theme so that we require to activate a child theme. Here is a screenshot for that:

image02

One important thing we do is that we import a style.css of parent theme on a child theme css. Like this:

@import url(“parent-theme-name/style.css”);

Create a CSS File.

Now the required things for child theme’s CSS file are:

  1. Theme Name
  2. Theme URI
  3. Description
  4. Author
  5. Author URI
  6. Template
  7. Version
  8. Tags
  9. Text DomainFile

When to use Child Themes?

Child themes can be used in different scenarios. We mostly use child theme to customise and modify a theme.

Advantages & Disadvantages of a Child Theme

Advantages

  1. We can easily customise a theme.
  2. All styles can be written on child theme css.
  3. We can do all types of changes on child theme.
  4. Child theme inherits parent theme style, functions file template and all features.
  5. We can easily update wordpress theme.
  6. This helps to increase the speed of development and reduces time to complete task.
  7. It is very flexible for customisation.
  8. If we forget any functionality or a code then parent theme is always available for making any correction.
  9. For any fallback, no need for recoding.
  10. Makes it Easy to Modify Popular Themes.

Disadvantage

  • Disadvantage of child theme is that we require time to understand a parent theme.

Conclusion

Now a days for any wordpress project we include a child theme. It is very easy to customise. So that we can fulfill our requirement easily.


CSS4 Selector

$
0
0

Overview

The CSS4 Selectors specializes a large number of revisions since CSS 3. That is the first draft of the spec likely changed in numerous ways before it becomes a recommendation itself and there are browser implementations. Let’s have a quick dig into the draft and see what has changed.

CSS is one probably the best bridge between web designers and developers so updates to the CSS spec are very exciting and there are many useful updates to be found. Let’s have a look at what new CSS4 selectors and features will be available to us in future browsers!

Some Useful Property In Css4 Selector

Matches-any pseudo-class

This matches-any pseudo-class  which takes as an argument a selector list. It lets you create sets of the selectors by groups which match all included the selectors.

Input:

<h1>Matches-any pseudo-class</h1>
<section>
    <h1>Section: Hello World!</h1>
    <p>But I must explain to you how...</p>
</section>
<article>
    <h2>Article: Hello World!</h2>
    <p>But I must explain to you how...</p>
</article>
<header>
    <h3>Header: Hello World!</h3>
    <p>But I must explain to you how...</p>
</header>
<aside>
    <h1>Aside: Hello World!</h1>
    <p>But I must explain to you how...</p>
</aside>

CSS:

:matches(section, article, aside) h1 {
    color: red;
}
:-moz-any(section, article, aside) h1 {
    color: red;
}
:-moz-any(section, article, aside) h2 {
    color: green;
}
:-moz-any(section, article, aside) h3 {
    color: blue;
}
:-webkit-any(section, article, aside) h1 {
    color: blue;
}

image-1

Indeterminate-value pseudo-class

This indeterminate-value pseudo-class which represents the indeterminate state of radio or checkbox elements. This state is the set of the checkbox or radio is neither checked or unchecked.

Input:

<h1>Indeterminate-value pseudo-class</h1>
<label for="test">Label</label>
<input type="checkbox" id="test" />

<script type="text/javascript">
    document.getElementById("test").indeterminate = true;
</script>

CSS:

:indeterminate {
    opacity: 1;
}

image-2

Attribute case-sensitivity

This attribute case-sensitivity selector is mostly equivalent to the CSS2 attribute selector but difference between to the case-sensitivity within to ASCII range. It selects an element using the given attribute value case-sensitivity.

Input:

<h1>Attribute case-sensitivity</h1>
<a href="test.pdf">Test</a>
<a href="test.PDF">Test</a>
<a href="test.pDF">Test</a>
<a href="test.html">Test</a>
<a href="test.xml">Test</a>

CSS:

a[href$="pdf" i] {
    color: red;
}

image-3

Direction pseudo-class

This dir pseudo-class will match elements by its direction based on the document     language. Currently these are left-to-right and right-to-left common value while left-to-right and right-to-left.

Input:

<h1>Direction pseudo-class</h1>
<div dir="ltr">Test</div>
<div dir="rtl">Testing</div>

CSS:

:dir(ltr) {
    color: green;
}
:dir(rtl) {
    color: blue;
}

image-4

Scope pseudo-class

This scope pseudo-class can be represented by any element that is in the contextual     references element set and if the contextual references element set is empty :scope is equivalent to :root.

Input:

<header>      
    <div>
        <style scoped>
            :scope { background-color: blue; }
        </style>
        <p>Inside the scope</p>
    </div>
    <div>
        <p>Outside of the scope</p>
    </div>
</header>

CSS:

:scope {
    background-color: #000;
}

image-5

How to create simple iMessage App

$
0
0

Overview

In this demo, I have mentioned that how we can able to use Message Extansion in iOS 10.

Once you launch application, it will open message screen. Where you can able to check see list of web pages name of “Yudiz Solution Pvt Ltd”.

If you want to send any webpage url as message, you just need to tap on webpage name, application will send that selected webpage in message. If you tap on that message, it will load webpage inside message application.

Topics

  1. Basic Understanding regarding ‘MSMessagesAppViewController’
  2. Supported iOS: 10.0 and above
  3. Supported Languages : Swift and Objective C
  4. How to create Demo App

Step 1: Create new Project

Create New Xcode Project and select iMessageApplication.

ScreenShot_1_1

ScreenShot_1_2

Once you create your application then just run the application to check what you are getting by default.

Once you run the application, in simulator, message application is appearing by default and inside that below “Hello World” text is there and your iMessage application name is there.

ScreenShot_1_3

Step 2: What you can see once you created Project

Here you can able to see total 4 folders in your new created Project.

ScreenShot_2_1

  1. iMessageDemo
  2. MessagesExtension
  3. Frameworks
  4. Products

Here you just need to use files which are there under ‘MessagesExtension’ folder for further development.

Step 3: Which functionality we will Develop

  • User will able to see our company name and its related webpage name in table view.
  • User just need to tap on webpage name to send links as message.
  • When user taps on that message, Link will be loaded in SFSafariViewController.

Step 4: UI Implementation

  • Open storyboard file
  • Remove “Hello World” label
  • Put one TableView in storyboard.

ScreenShot_4_1

Step 5: Add delegate and Datasource method of Tableview

  • In MessagesExtension folder, select ‘MessageCategoryVC.swift’ file.
  • Implement necessary UITableView Delegate and Datasource methods.

ScreenShot_5_1

Step 6: Prepare data which you like to display in Tableview

  • In this demo I am displaying webpage information of ‘Yudiz Solution Pvt Ltd’.
  • You can check that in “DataHandler.swift” file.

ScreenShot_6_1

Step 7: Apply data in Table View

In Step 6, I have created method to get data from my model class. Now its time to display those data in my table view.

So lets retrieve all data first and pass it to TableView.

ScreenShot_7_2

ScreenShot_7_1

Step 8: Conversation Handling Methods

There are many conversation handling methods are there provided by MSMessageAppViewController, I have listed all below.

override func willBecomeActive(with conversation: MSConversation)
		// Called when the extension is about to move from the inactive to active state.
        // This will happen when the extension is about to present UI.
        // Use this method to configure the extension and restore previously stored state.

override func didResignActive(with conversation: MSConversation)
        // Called when the extension is about to move from the active to inactive state.
        // This will happen when the user dissmises the extension, changes to a different
        // conversation or quits Messages.
        // Use this method to release shared resources, save user data, invalidate timers,
        // and store enough state information to restore your extension to its current state
        // in case it is terminated later.

override func didReceive(_ message: MSMessage, conversation: MSConversation)
        // Called when a message arrives that was generated by another instance of this
        // extension on a remote device.
        // Use this method to trigger UI updates in response to the message.

override func didStartSending(_ message: MSMessage, conversation: MSConversation)
        // Called when the user taps the send button.

override func didCancelSending(_ message: MSMessage, conversation: MSConversation) 
        // Called when the user deletes the message without sending it.
        // Use this to clean up state related to the deleted message.

override func willTransition(to presentationStyle: MSMessagesAppPresentationStyle)
        // Called before the extension transitions to a new presentation style.
        // Use this method to prepare for the change in presentation style.

override func didTransition(to presentationStyle: MSMessagesAppPresentationStyle)
        // Called after the extension transitions to a new presentation style.
        // Use this method to finalize any behaviors associated with the change in presentation style.

But for this demo we just need to use below two methods only.

override func willBecomeActive(with conversation: MSConversation)
override func willTransition(to presentationStyle: MSMessagesAppPresentationStyle)

In “willBecomeActive” method we will save all previous conversation.

In “willTransition” method we will open SFSafariView screen to load webpage from URL.

Step 9: Save Conversation

First create an global object of MSConversation.

ScreenShot_9_1

Now use this object to save all previous conversation which you can able to get from “willBecomeActive” method.

ScreenShot_9_2

Step 10: Send Webpage as Message

Now you have to apply some code in “didSelectRow” method of UITableView.

In this method an object of “MSMessage” and another object of “MSMessageTemplateLayout”

In “MSMessageTemplateLayout” object you have to pass details which you have to display in message screen.

So first we will pass CAPTION and SUBCAPTION in object of “MSMessageTemplateLayout”.

ScreenShot_10_1

Now we will set url property of “MSMessage” object.

ScreenShot_10_2

Now we will set layout property of “MSMessage” object.

ScreenShot_10_3

Our message object is ready now to send as Message. Now we just in to append this “MSMessage” object in our object of “MSConversation” which we just saw in STEP 9.

ScreenShot_10_4

Step 11: Lets run Application and Check

Once you run application you will able to see below screen

ScreenShot_11_1

ScreenShot_11_2

Now lets tap on any webpage name from the table view list.

Once you taps it will ask you permission to send this message. You have two option here. Either you can cancel the message or send message.

ScreenShot_11_3

ScreenShot_11_4

Now let’s check what happen if you tap on that sent message.

You will navigate to list view of all web pages of this application. Here we need to open webpage instead of this behaviour.

ScreenShot_11_5

So lets check how we can able to do this in our next step.

Step 12: Open Webpage when user taps on Message

We have to use “willTransition” conversation handling method to implement this feature. Right now this method do not contains any logic.

override func willTransition(to presentationStyle: MSMessagesAppPresentationStyle) {
    // Called before the extension transitions to a new presentation style.
    // Use this method to prepare for the change in presentation style.
}

Lets implement logic now.

override func willTransition(to presentationStyle: MSMessagesAppPresentationStyle) {
        guard presentationStyle == .expanded else { return }
        if let message = activeConversation?.selectedMessage, let url = message.url {
            safariVC = SFSafariViewController(url: url)
            present(safariVC!, animated: true, completion: nil)
        }
        // Called before the extension transitions to a new presentation style.
        // Use this method to prepare for the change in presentation style.
}

Step 13: Run App again. This is a final step. I Promise… :-)

  • Lets run application again.
  • Send any webpage first as message.
  • Tap on that message to open webpage. Now you can able to see webpage is loaded into message application.

ScreenShot_13_1

Biadu map integration in Android

$
0
0

Application Creation Procedure

Access the API console page, if you are not logged in Baidu account, will enter the Baidu account login page, as shown below:

image-1

Login to the API Console

Login will jump to the API console service, as shown below:

image-2

Create new Key

image-3

Select Android SDK as a Platform

image-4

Configure the Application

After selecting “Android SDK” as the application type, you need to configure the application’s security code, as shown in the following figure:

image-5

Get the Security Code

Security code composition rules: Android signature certificate sha1 value + packagename For example:

The SHA1: BB: 0D: the AC: 74: D3: 21: the E1: 43: 67: 71: 9B: 62: 91: the AF: the A1: 66: 6E: 44: 5D: 75

Package name: com.baidumap.demo

After entering the security code, click “OK” to complete the configuration of the application, you will get a created Key, please keep your application Key. At this point you can use the new Key to complete your development work.

Project Configuration Method

Step 1:

In the project app / libs directory into baidumapapi_vX_X_X.jar package, in the src / main / directory new jniLibs directory, the project will automatically load the src directory so dynamic library, put libBaiduMapSDK_vX_X_X_X.so as shown below , Note that the first three versions of jar and so must be the same, and to ensure that the use of a download folder in the two files, not different functional components of the jar or so cross-use.

image-6

So the configuration can also refer to the directory structure given demo, as shown below, in the app project path, the new libs, and in the libs directory into the corresponding different CPU architecture so the file. So the project does not automatically load the libs under so, need to compile the gradle, by adding the code: jniLibs.srcDir ‘libs’ to explain the path of the libs path.

image-7

Step 2:

Project configuration also need to integrate the jar package to their own projects, as shown in the figure above, into the libs directory. For each jar file, right – select Add As Library, into the project. Corresponding to the build.gradle generated project depends on the jar file description, as shown:

image-8

Jar configuration can also refer to eclipse method, the following operations:

Select File -> Project Structure from the menu bar.

In the Project Structure dialog box that pops up, select module, and then click the Dependencies tab.

Click on the green plus select File dependency. Then select the jar package to add to complete the above operation in the app directory under the build.gradle file, there will be the introduction of the class library, as shown above.

Show Baidu Map

Baidu map SDK for developers to provide a convenient interface to display Baidu map data, in the following steps, you can use in your application Baidu map data:

The first step: create and configure the project (see the specific methods of the project configuration section);

The second step: AndroidManifest add development key, the required permissions and other information;

  1. In the application to add development key
    <application >  
        < Meta - Data  
            Android : name = "com.baidu.lbsapi.API_KEY"   
            Android : value The = "Developer Key" />  
    </application >
  2. Add the required permissions
    < uses - permission Android : name = "android.permission.ACCESS_NETWORK_STATE" /> 
    < uses - permission Android: name = "android.permission.INTERNET android.permission.ACCESS_NETWORK_STATE" /> 
    < uses - permission Android : name = "com.android.launcher.permission .READ_SETTINGS " /> 
    < uses - permission Android: name = " android.permission.WRI " /> 
    < uses - permission Android : name = " android.permission.CHANGE_WIFI_STATE " /> 
    < uses - permission Android : name = " Android. permission.ACCESS_WIFI_STATE " /> 
    < uses - permission Android: name = " android.permission.GET_TASKS " /> 
    < uses - permission Android : name = " android.permission.WRITE_EXTERNAL_STORAGE " /> 
    < uses - permission Android: name = " Android .permission.WRITE_SETTINGS " />

    The third step, in the layout of the xml file to add the map control;
    < com. Baidu . Mapapi . Map . MapView   
        Android : id = "@ + id / bmapView"   
        Android : layout_width = "fill_parent"   
        Android : layout_height = "fill_parent"   
        Android : clickable = "true" />

    The fourth step is to initialize the Context global variable that the SDK refers to when the application is created:
    public  class MainActivity extends Activity {  
        @Override  
        protected void onCreate ( Bundle savedInstanceState ) {  
            Super onCreate ( savedInstanceState ) ;   
            // Before using the SDK each component initialization context information, passing the ApplicationContext   
            // Note that this method again setContentView way to achieve before  
            SDKInitializer. initialize ( getApplicationContext ( ) ) ;   
            setContentView ( R. layout . activity_main ) ;  
        }  
    }

    Note: need to call before using the SDK various functional components
    SDKInitializer.initialize (getApplicationContext ()) ;, so we recommend that the method on the Application of the initialization method

    The fifth step, create a map Activity, manage the map life cycle;

    public  class MainActivity extends Activity {   
         MapView mMapView = null ;  
        @Override  
        protected void onCreate ( Bundle savedInstanceState ) {  
            Super . onCreate ( savedInstanceState ) ;   
            // Before using the SDK each component initialization context information, passing the ApplicationContext   
            // Note that this method again setContentView way to achieve before  
            SDKInitializer. initialize ( getApplicationContext ( ) ) ;   
            setContentView ( R. layout . activity_main ) ;  
            // Get a reference to the map control  
            mMapView = ( MapView ) findViewById ( R. above mentioned id . bmapView ) ;  
        }  
        @Override  
        protected void onDestroy ( ) {  
            Super . onDestroy ( ) ;  
            // executed when the activity execution onDestroy mMapView.onDestroy (), to achieve the map lifecycle management  
            mMapView. onDestroy ( ) ;  
        }  
        @Override  
        protected void onResume ( ) {  
            Super . onResume ( ) ;  
            // executed when the activity execution onResume mMapView onResume (), map to achieve life-cycle management.  
            mMapView. onResume ( ) ;  
            }  
        @Override  
        protected void onPause ( ) {  
            Super . onPause ( ) ;  
            // executed when the activity execution onPause mMapView onPause (), map to achieve life-cycle management.  
            mMapView. onPause ( ) ;  
            }  
        }

After completing the above steps, run the program to display the following map in your application.

image-9

Boost up your WordPress Site

$
0
0

Why speed is important?

One second increase in page load than usual time will decrease the number of users to visit the site. To let users stay at your website, it should load within 2 seconds as per Google Recommendation.

Speed is considered as an essential factor in SEO of any website. Speed helps the website to rank higher in page search results. “More speed=Higher ranking” and “Higher ranking=More business sales”.

Now you have known why speed is important. So let’s focus on boosting up the site.

Choose better web hosting

Site’s performance depends upon your hosting of the website.You might wanna opt shared hosting for your site at the first glance as it provides unlimited bandwidth,domains,emails,etc.But as the name says “shared” the server,bandwidth,etc are shared among the other websites with same plan.What if your neighbouring site is getting more traffic? At that time server responds more to the neighbouring site than yours which in turn affect your site performance.

To overcome this you can choose Dedicated Hosting Service or Managed WordPress Hosting Service.

Use CDN

Site speed varies as per user’s location.(for e.g. A website server is located in London, so a London user will get faster loading of the site than the other users in different location.)

CDN(Content Delivery Network) helps you to reduce page load.It stores copy of your website at different location to serve webpage faster to nearby visitors.

Some of the CDN’s are MaxCDN and Cloudflare.

max-cdn

cloud-fare

Optimize Images

Users prefer to read content that has images in it.But images contain more size as compared to text.Higher size images when loading reduces speed of a webpage, so it needs to get compressed.

WordPress has several plugins that compresses bulk images such as:

  1. Smush It
  2. Tiny JPEG and PNG
  3. EWWW Image Optimizer

smush-it

tiny

ewww

Manage plugins

Get rid of plugins that are not in use as it puts load on server resources and increases size of backup file of your site.

Some of the problems can be solved by writing code in backend, so remove plugins that are related to it.

Enable Caching

Caching improves your site performance by keeping a copy into user’s browser and reducing download times of your files.

W3 Total Cache helps to increase the site performance.

w3-total-cache

Optimize Database

There can be lots of redundant data, unused tables, unnecessary post revisions, etc. in your site which increases the size of database.This affects on the fetching of data from the database.

WP- Optimize helps the site database to be fast and efficient.

wp-optimize

Update your WordPress site

WordPress keeps on updating.The current version of wordpress is 4.7.2.

Update your wordpress,themes and plugins regularly as it not only provides new features but it gives more security and fixes the bugs.This in turn prevents your site to be less hacked.(Note: If you want to customize code from the backend then create a child theme of the main theme and then copy the files into the child theme you want to customize.)

iMessage – Basic sticker App

$
0
0

Introduction

With latest iOS 10,Apple added new feature for third party developer called iMessage apps.Using that developer can make their own apps.

Apple has added new section [iMessage apps] at iTunes. This is only related to iMessage. iMessage apps will only be available on iOS, their content will still be viewable on macOS and watchOS devices.

iMessage extension has similar functionalities like photos, keyboard etc. extension. Only difference is that iMessage App Store exists on its own inside the Messages app, you can create an iMessage app without having to create an iOS app that goes on the user’s home screen.

Basic Sticker Packs

For people who just want to create a quick and easy iMessage sticker pack, Xcode provides a template to do so without having to write any code at all! This will be a great tool to enable graphic artists with no programming knowledge at all to create a sticker pack.

Messages framework supports three sticker sizes, which are displayed in a grid-based browser. In the Xcode Attributes inspector, pick one of the following sizes for your sticker pack:

Small. 100 x 100 points @3x (300 x 300 pixels).
Medium. 136 x 136 points @3x (408 x 408 pixels).
Large. 206 x 206 points @3x (618 x 618 pixels).

For optimal quality and performance, it provides sticker images of the size you choose.

There are, however, some limitations to the images you can use in your sticker packs:

The image must be a PNG, APNG, GIF, or JPEG fle.

The fle must be less than 500 KB.

For the best results, the image should not be smaller than 100 x 100 points or larger than 206 x 206 points.

Note

Always provide @3x images (300 x 300 pixels to 618 x 618 pixels). The system generates the @2x and @1x versions by downscaling the @3x images at runtime.

Step 1: Create Simple Xcode Project

For this demo, first I have created a Xcode project by selecting ‘Sticker Pack Application’ template type.

Screen_1

Step 2: Adding Stickers

Now open Stickers.xcstickers asset catalog in your project.

Screen_2

This folder will contain your iMessage application icon and all of the stickers in your pack.

Adding stickers to your application is as easy as dragging them into the Sticker Pack folder of your asset catalog.

If you want to add in an animated sticker using a series of images, you can right click in your Sticker Pack folder and choose the New Sticker Sequence option. With this in your sticker pack, you can drag to reorder individual frames.

Screen_3_2

Screen_3_1

Now open Attributes inspector of asset catalog in your project. You can change the name of your sticker pack and also the sticker size you are using.

Screen_4_2

Screen_4_1

Step 3: Run

Simply press the play button in the top-left corner of Xcode or press Command-R on your keyboard. Once the simulator has launched the Messages app, press on the app store button at the bottom of the screen to access your iMessage applications.

Once your app has been loaded you should see the stickers that we added are available to use and send.

Screen_5_1

Tapping on either of these stickers will add it to the current message, and from here you can press send.

Screen_5_2

It is very quick and easy to create sticker packs for iMessage in iOS 10 without needing to use any code at all.

output_1

Custom Sticker Applications

Step 1: Create Simple Xcode Project

For this demo, frst I have created a Xcode project by selecting ‘iMessage Application’ template type.

Screen_6

Once Xcode has created your project, you will see that you now have folders similar to that of an iOS app with an additional MessagesExtension folder.

The folder we are going to focus on is the MessageExtension folder, which at the moment contains the following fles:

MessagesViewController.swift which is the root view controller for your iMessage app’s UI.

MainInterface.storyboard where you can design your app’s interface easily.

Assets.xcassets which contains your iMessage app’s icon fles as well as any other image assets you need to use in your interface.

Info.plist for confguration values of your extension.

Step 2: Create Interface

For our example custom sticker application, we are just going to create our interface programmatically using the new MSStickerBrowserViewController class.

Open up your MessagesViewController.swift fle, and you will frstly see that your MessagesViewController class is a subclass of MSMessagesAppViewController, which itself is a subclass of UIViewController. All of UIKit is available for you to use in your iMessage applications.

The MessagesViewController class provides many callback methods which you can override to further customise the functionality of your application, but we don’t need to worry about these in this tutorial.

Now add MSStickerBrowserViewDataSource protocol.

extension MessagesViewController :
MSStickerBrowserViewDataSource{
   ...
}

Step 3: Adding Stickers

Drag the image fles into your project, and make sure that they are added to the MessagesExtension target. The fles need to be added to the target rather than to an asset catalog because that way we can load them from a URL, which is much easier when working with custom stickers.

Screen_7

Once you have added these fles, add the following code to your
MessagesViewController class:

var arrSticker :[MSSticker] = []
    func getStickers(){
        for i in 1...4 {
            if let url = Bundle.main.url(forResource:
"\(i)", withExtension: "gif") {
                do {
                    let sticker = try
MSSticker(contentsOfFileURL: url,
localizedDescription: "")
                    arrSticker.append(sticker)
                } catch {
                    print(error.localizedDescription)
                }
} }
        for i in 1...10 {
            if let url = Bundle.main.url(forResource:
"Sticker_\(i)", withExtension: "png") {
                do {
                    let sticker = try
MSSticker(contentsOfFileURL: url,
localizedDescription: "")
                    arrSticker.append(sticker)
                } catch {
                    print(error.localizedDescription)
} }
} }

With this code we simply create an MSSticker array to store our stickers and a function to load them from the local storage.

Next, add the following method to your class:

func createStickerBrowser(){
        let stickerBrowserVC =
MSStickerBrowserViewController(stickerSize: .small)
        addChildViewController(stickerBrowserVC)
        view.addSubview(stickerBrowserVC.view)
stickerBrowserVC.stickerBrowserView.backgroundColor =
UIColor.lightGray.withAlphaComponent(0.5)
stickerBrowserVC.stickerBrowserView.dataSource = self
        view.topAnchor.constraint(equalTo:
stickerBrowserVC.view.topAnchor).isActive = true
        view.bottomAnchor.constraint(equalTo:
stickerBrowserVC.view.bottomAnchor).isActive = true
        view.leftAnchor.constraint(equalTo:
stickerBrowserVC.view.leftAnchor).isActive = true
        view.rightAnchor.constraint(equalTo:
stickerBrowserVC.view.rightAnchor).isActive = true
}

With this code, we create an instance of the MSStickerBrowserViewController class and add this as a child of the root view controller in addition to constraining it to the full available height and width.

Next, we need to implement the required MSStickerBrowserViewDataSource methods to provide the necessary sticker information. To do so, add the following methods to your code:

func numberOfStickers(in stickerBrowserView:
MSStickerBrowserView) -> Int{
return arrSticker.count
    }
    func stickerBrowserView(_ stickerBrowserView:
MSStickerBrowserView, stickerAt index: Int) ->
MSSticker{
        return arrSticker[index]
    }

Lastly, so that all of our code is actually executed, replace your viewDidLoad method with the following:

override func viewDidLoad() {
        super.viewDidLoad()
        self.getStickers()
        self.createStickerBrowser()
}

Step 4: Run

Screen_8

output_2

In this tutorial, we only loaded local sticker images into our custom application for simplicity. One of the main advantages to using a custom sticker application, however, is that you can load sticker images from a remote server and even, through the use of other view controllers before showing your MSStickerBrowserViewController, let your users create their own stickers.

Custom Applications

In the last part of this tutorial, we are going to create a very basic iMessage application in order to create a unique message.

Step 1: Create Simple Xcode Project

For this demo, frst I have created a Xcode project by selecting ‘iMessage Application’ template type.

Screen_6

Step 2: UI

Once Xcode has created your project, Open up your MainInterface.storyboard fle in MessageExtension folder.

Remove default label and add as shown:

Screen_9

Please note that for your iMessage app to appear correctly on all device sizes, you will need to implement auto layout in your interfaces. In this example, I have constrained the button to the centre of the view controller.

Next open up the Assistant editor with your MessagesViewController.swift fle to create and give a touch up inside action for your button:

@IBAction func btnCreateImageAction(_ sender:
UIButton!){
}

Firstly, I need to introduce you to a few classes that are crucial when creating an iMessage app:

MSConversation: represents the currently open conversation. You can use this class in order to manipulate the conversation transcript, for example by inserting messages or getting the currently selected message.

MSMessage: represents a single message, whether created by you to insert into the conversation or already existing in the conversation.

MSMessageTemplateLayout: creates a message bubble for you to display your custom message in. As shown in the below image, this template layout has many properties and places for you to put your own content in order to customise your messages.

Screen_MSMessageTemplateLayout

It is important to note that the space in the top left of this layout will be flled by your iMessage app’s icon. Also, all of these properties are optional, and providing no caption strings at all will get rid of the bottom portion of the layout.

Add following method to your MessagesViewController class:

You will see that with this code, we frstly create the message layout and set the image and caption properties. Next, we create our MSMessage object to insert into the conversation.

func createImageForMessage() -> UIImage? {
        let bgv = UIView(frame: CGRect(x: 0, y: 0,
width: 300, height: 300))
        bgv.backgroundColor =
UIColor.lightGray.withAlphaComponent(0.5)
        let lbl = UILabel(frame: CGRect(x: 50, y: 50,
width: 200, height: 200))
3)
lbl.font = UIFont.systemFont(ofSize: 56.0)
lbl.backgroundColor = UIColor.clear
lbl.textColor = UIColor.white
lbl.text = "Yudiz"
lbl.shadowColor = UIColor.orange
lbl.shadowOffset = CGSize(width: 1, height:
lbl.textAlignment = .center
lbl.clipsToBounds = true
bgv.addSubview(lbl)
        bgv.frame.origin = CGPoint(x:
view.frame.size.width, y: view.frame.size.height)
        view.addSubview(bgv)
UIGraphicsBeginImageContextWithOptions(bgv.frame.size,
false, UIScreen.main.scale)
bgv.drawHierarchy(in: bgv.bounds,
afterScreenUpdates: true)
        let img =
UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        bgv.removeFromSuperview()
return img }
- Next, replace your btnCreateImageAction(_ sender: UIButton!) method with the following code:
          if let img = createImageForMessage(), let
conversation = activeConversation {
Ltd"
let layout = MSMessageTemplateLayout()
layout.image = img
layout.caption = "Yudiz Solutions Pvt
let message = MSMessage()
message.layout = layout
message.url = URL(string:
"http://www.yudiz.com")
            conversation.insert(message,
completionHandler: { (error) in
                print(error ?? "Inserted
successfully")
            })
}

Step 3: Run

Run your application and you will see an interface similar to the following:

Screen_10_1

Once you press the Create Message button, you should then also see the message layout bubble shown in the entry feld and available to send:

Screen_10_2

output_3

More Reference

Messages framework:

https://developer.apple.com/reference/messages

Viewing all 595 articles
Browse latest View live