Tuesday, October 11, 2016

iOS custom camera with Swift 3

This tutorial helps you create a custom iOS camera with overlay in Swift 3.  You can download the completed project here.

Step 1. Create the project, select Single View Application

Step 2. In the ViewController declare the following variables.
       
@IBOutlet weak var navigationBar: UINavigationBar!    
@IBOutlet weak var imgOverlay: UIImageView!    
@IBOutlet weak var btnCapture: UIButton!    

let captureSession = AVCaptureSession()    
let stillImageOutput = AVCaptureStillImageOutput()    
var previewLayer : AVCaptureVideoPreviewLayer?   

Step 3. Update the viewDidLoad() method as follows.

       
     override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        captureSession.sessionPreset = AVCaptureSessionPresetHigh
        
        if let devices = AVCaptureDevice.devices() as? [AVCaptureDevice] {
            // Loop through all the capture devices on this phone
            for device in devices {
                // Make sure this particular device supports video
                if (device.hasMediaType(AVMediaTypeVideo)) {
                    // Finally check the position and confirm we've got the back camera
                    if(device.position == AVCaptureDevicePosition.front) {
                        captureDevice = device
                        if captureDevice != nil {
                            print("Capture device found")
                            beginSession()
                        }
                    }
                }
            }
        }
    }
Step 4. Add the following functions in the ViewController

       
@IBAction func actionCameraCapture(_ sender: AnyObject) {
        
        print("Camera button pressed")
        saveToCamera()
    }
    
    func beginSession() {
        
        do {
            try captureSession.addInput(AVCaptureDeviceInput(device: captureDevice))
            stillImageOutput.outputSettings = [AVVideoCodecKey:AVVideoCodecJPEG]
            
            if captureSession.canAddOutput(stillImageOutput) {
                captureSession.addOutput(stillImageOutput)
            }
            
        }
        catch {
            print("error: \(error.localizedDescription)")
        }
        
        guard let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) else {
            print("no preview layer")
            return
        }
        
        self.view.layer.addSublayer(previewLayer)
        previewLayer.frame = self.view.layer.frame
        captureSession.startRunning()
        
        self.view.addSubview(navigationBar)
        self.view.addSubview(imgOverlay)
        self.view.addSubview(btnCapture)
    }
    
    func saveToCamera() {
        
        if let videoConnection = stillImageOutput.connection(withMediaType: AVMediaTypeVideo) {
            
            stillImageOutput.captureStillImageAsynchronously(from: videoConnection, completionHandler: { (CMSampleBuffer, Error) in
                if let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(CMSampleBuffer) {
                    
                    if let cameraImage = UIImage(data: imageData) {
                        
                        UIImageWriteToSavedPhotosAlbum(cameraImage, nil, nil, nil)                        
                    }
                }
            })
        }
    }

       
 

Step 5. Update your storyboard as shown in the image and connect the outlets.

Step 6. Hit "Command + R” :)
Once again, feel free to download the completed project here.

Saturday, December 20, 2014

Android Studio- Change The Keyboard Shortcuts - Mac OSX and Windows

Android developers are excited to know Android Studio 1.0. is the official Integrated Development Environment (IDE) from the Android team. It is built on the popular IntelliJ IDEA (Community Edition) Java IDE.

As we migrate from Eclipse, it is hard to adapt the default keyboard shortcuts in Android Studio.

Please follow the methods to change the keyboard shortcuts in Android Studio.

Mac OSX

Go to Android Studio Menu(1st Menu in the Top)  >  Preferences > Keymap.

Here we can change the style of keyboard we wish to use in Android Studio.


Windows
Go to File > Settings and look for Keymap.

Happy Coding :)

Monday, June 23, 2014

Copy a combination of image and text in IOS - UIPasteboard

A sample code snippet to copy a combination of image and text in IOS - UIPasteboard.

 NSMutableDictionary *photo = [NSMutableDictionary dictionary]; 
 NSMutableDictionary *text = [NSMutableDictionary dictionary]; 
 UIImage *image1 = [UIImage imageNamed:@"myimage.png"]; 
 NSData* imageData = UIImagePNGRepresentation(image1); 
 [photo setValue:imageData forKey:(NSString*)kUTTypePNG]; 
 [text setValue:@"Test String" forKey:(NSString *)kUTTypeUTF8PlainText]; 
 [[UIPasteboard generalPasteboard] setItems:[NSArray arrayWithObjects:photo, text, nil]]; 

Thursday, May 22, 2014

iOS Appstore Submission Checklist


1. App Name

The name of your app as it will appear on the App Store. Note that this name cannot be longer than 255 character.

2. SKU number

This must be unique among your apps; can include letters, numbers, hyphens, periods, and underscores.

3. Description 

A description of the app you are adding, detailing features and functionality. Descriptions cannot be longer than 4000 characters.

4. Keywords
 
One or more keywords that describe the app you are adding. When users search the App Store, the terms they enter are matched with keywords to return more accurate results. Separate multiple keywords with commas. Keywords cannot be edited once your binary is in review and cannot be longer than 100 characters.

5. Pricing and availability

This is where you set the price and release date for your app. (Click on the pricing matrix link to view the app prices for different tiers.)
    •    Tier 0 = Free
    •    Tier 1 = 0.99
    •    Tier 2 = 1.99
    •    Tier 3 = 2.99
    •    Tier 4 = 3.99
    •    etc.

6. Release date


This defaults to the current date, but you can set it to a date in the future if you like. 
If your app is approved before the release date you've set, then it won't be available in the App Store until that date.

7. App Version Number


Probably want 1.0 here for initial submission. This can't be changed once the app is in review.

8. Copyright info


For example, "2012 YourCompanyName"

9. Support URL

A URL that provides support for the app you are adding. This will be visible to customers on the App Store.

10. Marketing URL (Optional) 
  
A URL with information about the app you are adding. If provided, this will be visible to customers on the App Store.

11. Privacy Policy URL (Optional) 

A URL that links to your company's privacy policy. Privacy policies are recommended for all apps collecting user or device related data, and required for apps that offer auto-renewable or are designed for kids. or free subscriptions, or as otherwise required by law.

12. Contact Information
  
App Review Contact Information The person in your organization who should be contacted if the App Review team has any questions or needs additional information.

        First Name
        Last Name
        Email Address
        Phone Number
   
13. Review Notes (Optional)

Additional information about your app that can help during the review process. Include information that may be needed to test your app, such as app-specific settings and test registration or account details. The Review Notes field must not exceed 4000 bytes.

14. Demo Account Information (Optional)

The username and password for a full-access account. This account is used during the app review process and must not expire. Details for additional accounts should be included in the Review Notes field.

        Username
        Password

15. App Store Contact Information

To offer your app on the Korean App Store, you must provide additional information that will be displayed alongside your app. Note that this information will only appear in the Korean App Store.

Trade Name  A trade rep is someone within the company who has the authority to represent the company. Examples include the CEO, Representative Director, or other responsible officer within the company.

    Trade Rep First Name
    Trade Rep Last Name
    Address Line 1
    Address Line 2
    City
    State
    Postal Code
    Country
    Email
    Phone Number

16. Category

Use the App Store Category Definitions to choose the most appropriate category for your apps.

Primary Category
Secondary Category (Optional)

List of Categories
Books
Business
Catalogs
Education
Entertainment
Finance
Food & Drink
Games
Health & Fitness
Lifestyle
Medical
Music
Navigation
News
Photo & Video
Productivity
Reference
Social Networking
Sports
Travel
Utilities
Weather

17. Images

3.5-Inch Retina Display Screenshots
Screenshots for 3.5-inch iPhone and iPod touch Retina display must be 960x640, 960x600, 640x960 or 640x920 pixels, at least 72 DPI, in the RGB color space, and in the JPG or PNG format.

4-Inch Retina Display Screenshots
Screenshots for 4-inch iPhone 5 and iPod touch (5th generation) Retina display must be 1136x640, 1136x600, 640x1136 or 640x1096 pixels, at least 72 DPI, in the RGB color space, and in the JPG or PNG format.

iPad Screenshots iPad Screenshots must be .jpeg, .jpg, .tif, .tiff, or .png file that is 1024x768, 1024x748, 768x1024, 768x1004, 2048x1536, 2048x1496, 1536x2048 or 1536x2008 pixels, at least 72 DPI, and in the RGB color space.

Large App Icon (1024 x 1024 JPG, TIFF, or PNG ) - this image is for displaying in iTunes and on the App Store. It should match the icon in your app.

At least one screenshot. You can have up to five screenshots for each device type (iPhone, iPhone 5, and iPad).

Tuesday, December 10, 2013

How to Support Dynamic Type in iOS 7 Apps


Dynamic Type, is a feature added to iOS 7, that gives users the ability to choose a base text size. This text size will be used throughout the device including third-party applications. Here we discuss on How to Support Dynamic Type in iOS 7 Apps by working on a sample iOS app.

Step 1 - Create a View based iOS application.

Step 2 - Add a UILabel to the ViewController via story board and set the label outlet as contentLabel and add some text on it.

Step 3 - Goto ViewController.m and add the following code inside viewdidload.  This code will listen to the notification if text size is changed in the settings of the device.

  [[NSNotificationCenter defaultCenter]  
    addObserver:self  
    selector:@selector(changeTextSize:)  
    name:UIContentSizeCategoryDidChangeNotification  
    object:nil];  

Step 4 - Add the following function just below viewdidload.
- (void)changeTextSize:(NSNotification *)notification {  
   self.contentLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];  
 }  

Step 5 - You can test the feature by changing the Text Size. For that goto Settings App -> General -> Text Size and change the slider value. Come back to your app and check the font size of text in contentLabel .

Done :)

Thursday, December 5, 2013

An unexpected error occurred: ANDROID_BIN="${ANDROID_BIN:=$( which android )}" exited with 1 Deleting project... - PhoneGap

I was trying to create a new android project via command line in Mac and I got: "An error occurred: ANDROID_BIN="${ANDROID_BIN:=$( which android )}" exited with 1 Deleting project..."

Following was the command I used in Terminal to create a new Android PhoneGap Project. This works for iOS but not for Android.
 ./create ~/Desktop/MyPhoneGapApp com.companyname.myphonegapapp MyPhoneGapApp  
And I got an error as follows.
 An unexpected error occurred: ANDROID_BIN="${ANDROID_BIN:=$( which android )}" exited with 1 Deleting project... -  
Most probably this occurs because path to "tools" and "platform-tools"of the the Android SDK is not set to the PATH.

To fix this you should open the bash profile. Enter the following command in the terminal
 open ~/.bash_profile  

Now you will see the .bash_profile opened in the Text Editor. Enter the following line to your .bash_profile, save and close the file. Make sure to edit the following code to use the correct path of yours.
 PATH=$PATH:/Users/myaccount/Documents/adt-bundle-mac-x86_64/sdk/platform-tools:/Users/myaccount/Documents/adt-bundle-mac-x86_64/sdk/tools  
You should execute your .bash_profile to update your PATH.  Enter the following command in Terminal
 source ~/.bash_profile  
Now close and reopen your Teminal. Navigate to the bin folder of Android PhoneGap and enter the following command to create a PhoneGap Android Project.
 ./create ~/Desktop/MyPhoneGapApp com.companyname.myphonegapapp MyPhoneGapApp  
Done :)

Wednesday, December 4, 2013

How to Install PhoneGap in Mac and Create an iOS Project.

Please follow the steps below to install PhoneGap in mac OSX and create an iOS project.

Step 1 - Download and Install Node.js

Step 2 - Goto PhoneGap download page in your browser and download the latest version of PhoneGap and UnZip it.

Step 3 - Open Terminal in your mac and navigate to the folder where you downloaded PhoneGap.

Step 4 - From there navigate to the path in terminal \phonegap-2.9.1\phonegap-2.9.1\lib\ios\bin

Step 5 - Type the following command in Terminal

./create ~/Desktop/MyPhoneGapApp com.companyname.myphonegapapp MyPhoneGapApp

Parameters of the create command are

1 -
"~/Desktop/MyPhoneGapApp" Path to create new project
2 - "com.companyname.myphonegapapp" bundle name
3 - "
MyPhoneGapApp" Project nameThis will create an iOS PhoneGap project named MyPhoneGapApp in Desktop :)

Sunday, December 1, 2013

How To Integrate PFLogInViewController And PFSignUpViewController in iOS App

Please follow the previous tutorial, How To Integrate Parse With iOS App to get started with Parse in your iOS App.

In this tutorial, we are going to edit the Appdelegate.h and .m files to launch PFLogInViewController And PFSignUpViewController. 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  
  {  

   [Parse setApplicationId:@"YOUR_PARSE_APP_ID" clientKey:@"YOUR_CLIENT_KEY"];  
   self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];  

   // Override point for customization after application launch.  
   if ([PFUser currentUser]) // if user logged in.  

   {  
    self.homeViewController= [[HomeViewController alloc]initWithNibName:@"HomeViewController" bundle:nil];  
    self.navigationController = [[UINavigationController alloc]initWithRootViewController:self.homeViewController];  

   } else  
   {  
    self.logInViewController = [self getLoginViewController];  
    self.navigationController = [[UINavigationController alloc]initWithRootViewController:logInViewController];  
   }  

   self.window.rootViewController = self.navigationController;  
   [self.window makeKeyAndVisible];  

   return YES;  

  }   

Copy paste this method to Appdelegate.m
 - (PFLogInViewController *)getLoginViewController
 {
   PFLogInViewController *loginController= [[PFLogInViewController alloc] init];
   [loginController setDelegate:self];
   loginController.logInView.logo = nil;

   loginController.fields = PFLogInFieldsUsernameAndPassword
   | PFLogInFieldsLogInButton
   | PFLogInFieldsSignUpButton
   | PFLogInFieldsPasswordForgotten;

   self.signUpViewController = [[PFSignUpViewController alloc] init];
   [signUpViewController setDelegate:self];

   signUpViewController.fields = PFSignUpFieldsUsernameAndPassword
   | PFSignUpFieldsSignUpButton|PFSignUpFieldsDismissButton;

   signUpViewController.signUpView.logo = nil;
   [loginController setSignUpController:signUpViewController];
   return loginController;
 }


Login and SignUp screens are set. Now we should include delegates for Login and SignUp.

Sent to the delegate to determine whether the log in request should be submitted to the server.
 - (BOOL)logInViewController:(PFLogInViewController *)logInController shouldBeginLogInWithUsername:(NSString *)username password:(NSString *)password { 
   // Validate username and pasword field.
   if (username && password && username.length != 0 && password.length != 0) { 
     return YES; // Begin login process 
   } 

   [[[UIAlertView alloc] initWithTitle:@"Missing Information" 
                 message:@"Make sure you fill out all of the information!" 
                 delegate:nil 
            cancelButtonTitle:@"ok" 
            otherButtonTitles:nil] show]; 
   return NO; // Interrupt login process 
 } 

Sent to the delegate when a PFUser is logged in.
 - (void)logInViewController:(PFLogInViewController *)logInController didLogInUser:(PFUser *)user {

   NSLog(@"Login sucessfull !! and username is %@",user.username);
   self.homeViewController= [[HomeViewController alloc]initWithNibName:@"HomeViewController" bundle:nil]; 
   [self.navigationController pushViewController:self.homeViewController animated:YES];\
 }

Sent to the delegate when the log in attempt fails.
- (void)logInViewController:(PFLogInViewController *)logInController didFailToLogInWithError:(NSError *)error 
{
   NSLog(@"Failed to log in...");
}

Sent to the delegate when the log in screen is dismissed.
- (void)logInViewControllerDidCancelLogIn:(PFLogInViewController *)logInController 
{
   NSLog(@"Canceled log in...");
}

Sent to the delegate to determine whether the sign up request should be submitted to the server.
- (BOOL)signUpViewController:(PFSignUpViewController *)signUpController shouldBeginSignUp:(NSDictionary *)info { 
   BOOL informationComplete = YES; 
   //Validate all datafields.
   for (id key in info) { 
     NSString *field = [info objectForKey:key]; 
     if (!field || field.length == 0) { // check completion 
       informationComplete = NO; 
       break; 
     } 
   } 

   // Display an alert if validation failed
   if (!informationComplete) { 
     [[[UIAlertView alloc] initWithTitle:@"Missing Information" 
                   message:@"Make sure you fill out all of the information!" 
                   delegate:nil 
              cancelButtonTitle:@"ok" 
              otherButtonTitles:nil] show]; 
   } 
   return informationComplete; 
 } 

Sent to the delegate when a PFUser is signed up.
- (void)signUpViewController:(PFSignUpViewController *)signUpController didSignUpUser:(PFUser *)user { 
   // SignUp sucessfull, Now dismiss the PFSignUpViewController 
   [self.signUpViewController dismissViewControllerAnimated:YES completion:nil]; 
} 

Sent to the delegate when the sign up attempt fails.
- (void)signUpViewController:(PFSignUpViewController *)signUpController didFailToSignUpWithError:(NSError *)error { 
   NSLog(@"Failed to sign up..."); 
 } 

Sent to the delegate when the sign up screen is dismissed.
- (void)signUpViewControllerDidCancelSignUp:(PFSignUpViewController *)signUpController { 
   NSLog(@"User dismissed the signUpViewController"); 
 } 

Done :)

Monday, November 25, 2013

How To Integrate Parse With iOS App

This post is to discuss on Integrating Parse with iOS app. If you are planning to create a fresh iOS project with Parse then download the Starter project here. If you want integrate the Parse with an existing iOS app, then please go through the steps below.

Step 1. Parse SignUp
Step 2. Move to Dashboard
Step 3. Create a New App
Step 4. Copy Application ID, Client Key and REST API Key to a text file.

Open your iOS application and paste the following code in the didFinishLaunchingWithOptions method of AppDelegate.m

  [Parse setApplicationId:@"Your_App_Id" clientKey:@"Your_Client_Key"];  

Our method looks as follows. Don't forget to replace the placeholder with your App Id and Client Key :)

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  
 {  
   [Parse setApplicationId:@"Your_App_Id" clientKey:@"Your_Client_Key"];  
   return YES;  
 }  

Add following code to the top of AppDelegate.m file.
 #import <Parse/Parse.h>  

Now we should download the Parse iOS SDK and add the Parse framework to our project. Also add the following libraries to the iOS project.
  • AudioToolbox.framework   
  • CFNetwork.framework    
  • SystemConfiguration.framework
  • CoreGraphics.framework  
  • CoreLocation.framework    
  • MobileCoreServices.framework    
  • QuartzCore.framework    
  • Security.framework    
  • StoreKit.framework     
  • libz.1.1.3.dylib   

Run your project and make sure there is no errors.
Login to your Parse account and goto the DataBrowser tab to check your back-end data.

Done :)

Friday, November 22, 2013

Tizen the new mobile OS !!!

The new Tizen mobile operating system is supported by Samsung and now a Tizen smartphone bearing model number SC-03F has come to light.

Most mobile phone users have never heard of Tizen.  Tizen is a project within the Linux Foundation and is governed by a Technical Steering Group (TSG) composed of Samsung and Intel. Samsung has already allocated USD $4 million towards the development of various apps from developers.

Tizen allows developers to program in HTML5, CSS, and Javascript) for its upcoming smartphone
Samsung has already allocated USD $4 million towards the development of various apps from developers (Tizen allows developers to program in HTML5, CSS, and Javascript) for its upcoming smartphone.

Read more at: http://www.firstpost.com/tech/samsung-tizen-and-the-internet-of-things-revolution-1233687.html?utm_source=ref_article
Samsung has already allocated USD $4 million towards the development of various apps from developers (Tizen allows developers to program in HTML5, CSS, and Javascript) for its upcoming smartphone.

Read more at: http://www.firstpost.com/tech/samsung-tizen-and-the-internet-of-things-revolution-1233687.html?utm_source=ref_article

Company / developer  :   Linux Foundation, Tizen Association, Samsung, Intel

OS family  :   Linux

Source model     Operating system: Open-source

SDK: Closed-source

Initial release :  January 5, 2012

Target Device :     PCs, tablets, smartphones, GPS smartnav, in-vehicle infotainment, smart TV

Available programming languages(s) :  HTML5, C, C++

Package manager :  RPM Package Manager

Supported platforms :  ARM and x86

Kernel type :  Monolithic (Linux)

Default user interface : Graphical (Native and Web applications)

License Operating system :  GPLv2, LGPL, Apache License, BSD, Flora License

SDK : Freeware

Official website :    www.tizen.org