multipeer1
Uncategorized

Hey Folks,

I have been recently exploring the Multipeer connectivity framework iOS and i thought sharing the same would be really helpful for those who have unexplored this framework.

Well First things first. Few questions & answers :

  • Why use Multipeer connectivity ?
    • If you are looking forward for connecting two or more iPhones via bluetooth or wifi and that need file sharing or needs something like chat application, you are on right track
  • What is Multipeer ?
    • Multipeer framework is build for iPhone to connect peripheral devices, We can use it to connect to iPhones, iWatch, iBeacons and other bluetooth accessories too. Its basic framework that defines protocol for peer to peer connections

Enough talking, lets dig into coding part.

Pre-requisite for implementing peer to peer connectivity.

  • iPhone (Physical Device)
  • Simulator OR another iPhone or Bluetooth peripheral devices
  • Basic overview of Peer commands and full understanding of sending bytes in packets through encryptions. (Lolz just kidding)

So lets Start.

Step 1 : Add Multipeer Connectivity Framework

Screen Shot 2016-06-17 at 9.10.09 PM

Step 2 : Create two files Master & Slave

Also download Multipeer this 2 files

Master would be searching for another device & slave would advertise itself that i am available for connection. (Same like Groom/Bride Searching :P).

So here is code for Master :

#import <MultipeerConnectivity/MultipeerConnectivity.h>
@import MultipeerConnectivity;
@interface MasterVC : UIViewController <MCBrowserViewControllerDelegate>
- (IBAction)browseForDevices:(id)sender;
@end

For Master.m

// in your appdelegate

@property (nonatomic, strong) MPManager *mpManager;

_mpManager = [[MPManager alloc] init];

// In your master.m

- (IBAction)browseForDevices:(id)sender {
    [[_appDelegate mpManager] setupMCBrowser];
    [[[_appDelegate mpManager] browser] setDelegate:self];
    [self presentViewController:[[_appDelegate mpManager] browser] animated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didStartReceivingResourceWithNotification:)
                                                 name:@"MCDidStartReceivingResourceNotification"
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(updateReceivingProgressWithNotification:)
                                                 name:@"MCReceivingProgressNotification"
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didFinishReceivingResourceWithNotification:)
                                                 name:@"didFinishReceivingResourceNotification"
                                               object:nil];
}

#pragma mark - Public method implementation

- (IBAction)browseForDevices:(id)sender {
    [[_appDelegate mpManager] setupMCBrowser];
    [[[_appDelegate mpManager] browser] setDelegate:self];
    [self presentViewController:[[_appDelegate mpManager] browser] animated:YES completion:nil];
}


#pragma mark - MCBrowserViewControllerDelegate method implementation

-(void)browserViewControllerDidFinish:(MCBrowserViewController *)browserViewController{
    [_appDelegate.mpManager.browser dismissViewControllerAnimated:YES completion:nil];
    [_tblConnectedDevices reloadData];
}


-(void)browserViewControllerWasCancelled:(MCBrowserViewController *)browserViewController{
    [_appDelegate.mpManager.browser dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - Private method implementation

-(void)peerDidChangeStateWithNotification:(NSNotification *)notification{
    MCPeerID *peerID = [[notification userInfo] objectForKey:@"peerID"];
    NSString *peerDisplayName = peerID.displayName;
    MCSessionState state = [[[notification userInfo] objectForKey:@"state"] intValue];
    
    if (state != MCSessionStateConnecting) {
        if (state == MCSessionStateConnected) {
            [_arrConnectedDevices addObject:peerDisplayName];
        }
        else if (state == MCSessionStateNotConnected){
            if ([_arrConnectedDevices count] > 0) {
                @try {
                    int indexOfPeer = [_arrConnectedDevices indexOfObject:peerDisplayName];
                    [_arrConnectedDevices removeObjectAtIndex:indexOfPeer];
                } @catch (NSException *exception) {
                    
                } @finally {
                    
                }
                
            }
        }
        [_tblConnectedDevices reloadData];
        
        BOOL peersExist = ([[_appDelegate.mpManager.session connectedPeers] count] == 0);
    }
}

And For Slave

- (void)viewDidLoad {
    [super viewDidLoad];
    _appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [[_appDelegate mpManager] setupPeerAndSessionWithDisplayName:[UIDevice currentDevice].name];
    [[_appDelegate mpManager] advertiseSelf:YES];
}

-(void)didStartReceivingResourceWithNotification:(NSNotification *)notification{


}
-(void)didFinishReceivingResourceWithNotification:(NSNotification *)notification{

}

Step 3 : Send Data to Slave Device

NSData *dataToSend = [@"play" dataUsingEncoding:NSUTF8StringEncoding];
    NSArray *allPeers = _appDelegate.mpManager.session.connectedPeers;
    NSError *error;
    
    [_appDelegate.mpManager.session sendData:dataToSend
                                     toPeers:allPeers
                                    withMode:MCSessionSendDataReliable
                                       error:&error];

Step 4 : Test & Debug :)

Happy Multipeering. Feel free to contact me.

screen-shots-on-mobile_01
Uncategorized

Hello readers,

Today i am going to show, what could happen if you take a screenshot of any app content for some user. Snapchat users get notified that this user has taken a screenshot of your post.

This is what we are going to implement.

It is not that hard as it sounds, iOS 7.0 and later gives you an observer in NSNotificationCenter named UIApplicationUserDidTakeScreenshotNotification.

Just add this observer in the view did load and you can add a selector in this to perform any other task after a screenshot is taken.

Add the following code in the ViewDidLoad of you view controller.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(screenshotDetected) name:UIApplicationUserDidTakeScreenshotNotification object:nil];
-(void)anotherAlert {
    UIAlertController *alertController = [UIAlertController
                                          alertControllerWithTitle:@"Hey!"
                                          message:@"Did you smile...???"
                                          preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction
                               actionWithTitle:NSLocalizedString(@"Lets see", @"OK action")
                               style:UIAlertActionStyleDefault
                               handler:^(UIAlertAction *action)
                               {
                                   NSLog(@"OK action");
                               }];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

You can perform any selector in this, i have added an alert controller, you can get the details of the user logged in, and can perform a notification.

More in this screenshot stuff, i am currently trying to take a picture from the front camera, when a screenshot is taken.

screen-shot
Uncategorized

Hello again readers, we were just thinking a new category to our blog posts, so here we bring you a post on watchOS. Yes this post will guide you through the basics of how to develop an app for the Apple watch.

This post will help you create a simple table view which will display a label and a detail Interface controller which will contain the details of the cell selected in the table view.

Simulator Screen Shot Sep 27, 2016, 10.55.44 AM

Tables basically shows the list of data whose contents changes dynamically. The class from which it inherits is WKInterfaceTable class. Note that tables on watch OS supports only single columns.

The layout should be set in the interface of the watch extension and the data to be displayed should be displayed runtime.

Screen Shot 2016-09-27 at 11.07.36 AM

MainWC is the Scene which will be displayed first as the watch app launches, I have placed a row controller and a label in it called “Country Name”, give the outlet to this label in the row controller class. This will be the custom class for you row controller. You can add one or more row controllers in the Scene as per your requirement. The row controller is a template used for displaying the content in the app at run time.

For this first we need to determine the number of rows that will be displayed in the app. The method in which we pass the number of rows is setNumberOfRows:withRowType: and we can use this to iterate over the total number and add content on each row with rowControllerAtIndex:.

This is the array I have used to insert the data.

arrWeekDay = [[NSMutableArray alloc] initWithObjects:@"Sunday",@"Monday",@"Tuesday",@"Wednesday",@"Thursday",@"Friday",@"Saturday", nil];

[self.weekName setNumberOfRows:arrWeekDay.count withRowType:@"city"];
NSInteger rowCount = self.weekName.numberOfRows;
// Iterate over the rows and set the label for each one.
for (NSInteger i = 0; i < rowCount ; i++) {
    // Get the to-do item data.
    NSString* itemText = arrWeekDay[i];
    // Assign the text to the row's label.
    WeekDay* row = [self.weekName rowControllerAtIndex:i];
    [row.lblName setText:itemText];
}

Now the part is running the watch app. Go to the target selection in Xcode and select the watch extension. Set the device as specified, iPhone 7 + Apple Watch Series 2 (this will be shown if you have xcode 8, in Xcode 7.2 iPhone 7 will not be there.) Hit the play button.

You will be shown a new simulator specially made for watch, the watch app run there.

          Simulator Screen Shot Sep 27, 2016, 10.56.50 AM          Simulator Screen Shot Sep 27, 2016, 10.56.34 AM

Now we will see what can we do if we select the row of this table,

There is a similar method as for the iOS, didSelectRowAtIndexPath for the WatchOS called didselectrowatindex. This is how you use it,

-(void)table:(WKInterfaceTable *)countryName didSelectRowAtIndex:(NSInteger)rowIndex
{
    NSString *data = [arrCityName objectAtIndex:rowIndex];
    [self presentControllerWithName:@"detailWC" context:data];
}

Here the present controller with name will present the scene and the context will send the data to the next presenting controller. We can use this data in the next controller.

Here is have passed the selected day to the next controller and displayed it through the context in the next controller in a label.

zRun it again and select any day, a new interface will be presented, with the day you selected as the label in it.
Simulator Screen Shot Sep 27, 2016, 11.56.47 AM          Simulator Screen Shot Sep 27, 2016, 11.56.42 AM

Thats all about how to display data in tables in WatchOs, for further practice try to generate different results on the select, calculations with the help of the data from frameworks. Thanks.

cordova
Uncategorized

Hey Folks,

Hope you are enjoying the tech post from my blogs, Few days ago i got opportunity to develop the Bluetooth TSL SDK’s Hand held Scanner Cordova plugin for iPhone. And that was exiting work for me. So i decided to write a blog which will show you how can we actually develop a Simple Cordova/PhoneGap plugin in iOS.

This will be very simple yet effective blog. Before moving ahead please keep in mind following pre-requisites.

  • xCode & iPhone Application Knowledge
  • Basic Knowledge of Cordova/PhoneGap
  • NodeJS installed on your MAC
  • Cordova installed on your MAC
  • Basic Knowledge of JavaScript & HTML

So lets dive into our first PhoneGAP / Cordova Plugin development. So here is the basic understanding of why do we need phonegap/cordova plugins and how can we bridge between them.

So Whats the Plugin ? Well Cordova/ PhoneGap is sued for developing hybrid application through extensive use of HTML & JavaScripts. And this apps can be easily deployed into various platforms like iPhone, Android, Windows, Blackberry and many more. But for accessing device hardware specific functionality PhoneGap/Cordova has created Plugins which can convert the JavaScript function call into iPhone/Android/Windows/Blackberry SDK calls.

So we will be learning this today. So lets deep dive into the coding

Step 1 : Create Cordova Project

cordova create plugin com.plugin Plugin
cd plugin/

Step 2 : Add iOS Platform

cordova platform add iOS

Step 3 : Adding Your Plugin into Config.xml

<!-- My custom plugin Start -->

    <feature name="MyResult">

        <param name="ios-package" value="MyResult" />

    </feature>

 <!-- My custom plugin End -->

Step 4 : Creating MyResult.h & MyResult.m classes

Here we need to inherit ‘CDVPlugin’ class into our MyResult.h

#import <Foundation/Foundation.h>
#import <Cordova/CDV.h>
@interface MyResult : CDVPlugin
// This will return the file contents in a JSON object via the getFileContents utility method
- (void) calcMe:(CDVInvokedUrlCommand *)command;

@end
#import "MyResult.h"

@implementation MyResult
-(void)calcMe:(CDVInvokedUrlCommand *)command{
    NSDictionary *jsonObj = [ [NSDictionary alloc]
                             initWithObjects:@[@"10" ] forKeys:@[@"result" ]
                             ];
    
    CDVPluginResult *pluginResult = [ CDVPluginResult
                                     resultWithStatus    : CDVCommandStatus_OK
                                     messageAsDictionary : jsonObj
                                     ];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
@end

Step 5 : Writing JavaScripts

Here we can call the calcMe function of our MyResult.h class through this syntax of

Cordova cordova.exec(success function, Failure function,Class Name,Function name,Arguments);

 onDeviceReady: function() {
        app.receivedEvent('deviceready');
        app.getReults();
    },

getReults: function(){
        cordova.exec(
                     function callback(data){
                        alert(data.result);
                     },
                     function errorHandler(err) {
                        alert('Error');
                     },
                     'MyResult',
                      'calcMe',
                     []
        );
    }

And your Final index.js file will look like below

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
        app.getReults();
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    },
    // Calling our own function
    getReults: function(){
        cordova.exec(
                     function callback(data){
                        alert(data.result);
                     },
                     function errorHandler(err) {
                        alert('Error');
                     },
                     'MyResult',
                      'calcMe',
                     []
        );
    }
};

app.initialize();

Step 6 : You are now Cordova/PhoneGap Developer : Cheers :)

You can download plugin from plugin.

Hope you have enjoyed this tutorial. There is more coming up stay tuned.

icloud-intro
Uncategorized

Have you been wondering how to actually integrate the iCloud storage in your Application ? Here is quick, short yet effective tutorial for the new bee.

Why Do we need iCloud Storage in my app :

  • Do you need to restore the data of the user even if user uninstalls your app ?
  • Do you want the user to logged into the application through different devices yet the data should be sync without web service ?
  • Do you want to store small bunch of data without creating web services ?

If the answers to above question is affirmative than feel free to integrate iCloud and follow this sort yet effective tutorial

Pre-requisite (A big hurdle) :

To integrate iCloud into your application you will need

  1. Apple Developer Account (Paid Account :P)
  2. Developer Certificate
  3. Bundle ID with iCloud Enabled
  4. Provisioning Profile with Above Certificate & Bundle ID
  5. Actual device to Test the APP

Notes : I would not prefer to use Wild Card Bundle ID & provisioning Profile to integrate iCloud/

Steps :

  1. Creating the Bundle Identifier :

    Screen Shot 2015-07-28 at 2.43.13 pm

    Screen Shot 2015-07-28 at 2.43.23 pm

    You will need to enable the iCloud in Your bundle identifier that will be needed.

  2. Setting up the basic application

    So you have set up the bundle ID, you are having the certificates and you have the provisioning profile with above certificates and bundle id. That means we can get our hand dirty into iCloud Application coding. Lets start with the basic setup. Follow the below screenshot to setup the basic app.

    1) Select the target-> general and check if cloudKit.framework is included as per below screenshot :

    Screen Shot 2015-07-28 at 4.55.32 pm

    2) Select target-> Category and enable iCloud -> KeyValue Storage And check if All 4 steps are tick if not like below screenshot click on Fix issue. (You will need team to be added in order to fix this issues)

    Screen Shot 2015-07-28 at 4.55.49 pm

    3) Check if Entitlement File is created and setup which will look like below :

    Screen Shot 2015-07-28 at 4.56.39 pm

  3. Writing the actual Code

    I hope you have followed me till now. Now lets dive deep into coding part. And its not complicated :P. I hope you are aware of NSUserDefaults. This syntax is similar to that and you will enjoy coding for iCloud.

    Lets look at the functions below :

    @property (strong, nonatomic) NSMutableArray *notes;
    
    - (NSArray *)notes
    {
        if (_notes) {
            return _notes;
        } 
        _notes = [[[NSUbiquitousKeyValueStore defaultStore] arrayForKey:@"AVAILABLE_NOTES"] mutableCopy];
        if (!_notes) _notes = [NSMutableArray array];
        return _notes;
    }
    
    
    -(IBAction)writeToiCloud:(id)sender
    
    {
        _notes = [[[NSUbiquitousKeyValueStore defaultStore] arrayForKey:@"AVAILABLE_NOTES"] mutableCopy];
        if(!_notes)
        {
            _notes=[[NSMutableArray alloc] init];
        }
        
        [_notes addObject:@"test1"];
        [[NSUbiquitousKeyValueStore defaultStore] setArray:self.notes forKey:@"AVAILABLE_NOTES"];
    }
    -(IBAction)readFromiCloud:(id)sender
    
    {
        _notes=[[NSMutableArray alloc] init];
        [[NSUbiquitousKeyValueStore defaultStore] synchronize];
       _notes = [[[NSUbiquitousKeyValueStore defaultStore] arrayForKey:@"AVAILABLE_NOTES"] mutableCopy];
        NSLog(@"%@",[self.notes description]);
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Array data" message:[NSString stringWithFormat:@"%@",_notes] delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
    }

    Here NSUbiquitousKeyValueStore actually is used to perform iCloud Read/Write Operations. Do not forget to bind this to touchUpInside event of Button.

  4. Testing Your App.

    Install into your device click on write button, read button Close App. UnInstall the app. Re-install the app and than perform Read operation if you are able to read you are iCloud Master 😛

ios-9-download
Uncategorized

Multitasking Enhancements for iPAD

For Multitasking on iPAD, iOS 9 has introduced bunch of new views which are :

  • Slide Overview : Talking about Slide view, it lets users pick a secondary app and quickly interact with it
  • Split View : It provides users the ability to use two apps side by side on iPad Air 2
  • Picture in Picture View : (also known as PiP) lets users watch video in a window that floats above other onscreen apps.

3D Touch

3D Touch is all new exiting feature of iOS9, this will change the way we use the touch gesture. On supported devices, people can quickly choose app-specific actions from the Home screen by pressing on the app icon. Within an app, people can use various pressures to get a preview of an item, open the item in a separate view, and access related actions

Search

This is all new exiting feature where in the User can search within app, even news. This will definitely eliminate need of Google. Search in iOS 9 gives users great new ways to access information inside of your app, even when it isn’t installed. When you make your content searchable, users can access activities and content deep within your app through Spotlight and Safari search results, Handoff, and Siri suggestions.

Gaming

Gaming is taken to all new level in iOS 9. There are minor improvisations on Gaming but will help the developers to create new and exiting games. iOS9 includes several technology improvements that make it easier than ever to implement your game’s graphics and audio features. Take advantage of high-level frameworks for ease-of-development, or use new low-level enhancements to harness the power of the GPU.

App Thinning

I have already written a brief blog on App Thinning which you can find it here. This feature will help to reduce the application size to a big extend.

Support for Right to Left Languages

iOS 9 brings comprehensive support for right-to-left languages, which makes it easier for you to provide a flipped user interface. This feature will help developer to create actual multilingual application

App Transport Security

App Transport Security (ATS) enforces best practices in the secure connections between an app and its back end. ATS prevents accidental disclosure, provides secure default behavior, and is easy to adopt; it is also on by default in iOS 9 and OS X v10.11.

size-class
Uncategorized

Hello Readers,

Lets, just recall the steps we follow when starting a new project, most of the time we unselect the Size Classes selection given just below the Auto Layout option, Today we will see what it is actually used for and see how it can be useful for our apps.

The size Classes is a new technology introduced in iOS 8, which allows users to specify width and height combinations to the design for different devices and even orientations. Prior to iOS 8 the developers had to use multiple storyboards and write code for orientation checks (Landscape / Portrait) to use different UILayout as per device / orientation. This tutorial will guide through the size classes and how to use its compact / regular heights for which devices.

Designing the view

Start by creating a new single view application, enter the details such as product name, organization name, organization identifier then select the language as swift and make sure that the devices is selected Universal. Go to the storyboard and edit the main view color to light blue and add 4 buttons, place each at one corner of the view. Name those buttons as one, two, three, four or as per their position in the view – top-left,top-right, bottom-left and bottom-right. The storyboard should look like this.Screen Shot 2015-10-27 at 11.17.47 AM

Now build and run your project in iPhone 5s simulator. You will see that the two right buttons are not visible on the screen. This is because The layout was designed with the Size class for Any-width and Any-height. Now, let’s pin the buttons to the corners.

Now make sure that the interface builder has these items selected, the Auto-Layout and the Size-Classes, as shown below.Screen Shot 2015-10-27 at 11.21.51 AM

Select the top-left button and use the right click and start dragging to the left, select the “leading space to container margin”, and do the same dragging towards the top and add the “Top space to layout guide” constraint for the button.

Add the following constraints for the other Buttons:

  • top-right button -> Trailing Space to Container Margin, Top Space to Top Layout Guide
  • bottom-left button -> Leading Space to Container Margin, Bottom Space to Bottom Layout Guide
  • bottom-right button -> Trailing Space to Container Margin, Bottom Space to Bottom Layout Guide

After this build and run the project, in iPhone and iPad check for all orientations too, the buttons will be set to their margins.

Now if you take your attention on the bottom of the screen you will see something like this, this “wAny hAny” is the default size class layout selected.

Screen Shot 2015-10-27 at 1.28.50 PM

Click on it a screen like below will open, on which when you drag your mouse pointer, different selection can be made. These are the different layout in the size classes which the Xcode offers.

Size Classes

The size classes tool presents a grid of nine tiles. When you select the size class Any for either dimension, green dots in tiles indicate areas where your base value design specifications take effect for this size combination. For example, for the Any Width | Any Height combination, green dots in all of the tiles show that the layout constraints and views that you specify on the Interface Builder canvas apply to every device size and orientation.

When you select either the compact size class or the regular size class for either dimension, any change you make to your layout for that dimension overrides the base layout specifications. For example, when you select the Compact Width | Any Height combination, the constraints that you change—and any views that you add or remove—apply only to compact width layouts, for any height.

When you select a specific size class for each dimension, a single green dot in a tile and the label Final Values indicate that your layout values apply exclusively to the shaded tiles on the grid. For example, when you select Compact Width | Regular Height, changes to layout constraints and views apply exclusively to iPhone devices in portrait orientation.

any-any           compact-any          compact-regular

The following image will show you the width and the height layout the devices use in their landscape and portrait mode.

size classes

Select the “wCompact hCompact” in the size class, you will notice that the size of the controller is reduced. this size class can be used for all iPhones except for iPhone 6 Plus.

Adding a button for Landscape orientation only

Now add a button at the top center of the view, name it “Top-Center”. Also give auto layout constraints to it, These constraints will allow the button to be placed at a fixed distance from the top and stay at the center.

  • Top Space to Top Layout Guide
  • Center Horizontally in Container

Now the Compact – Compact size class combination is for iPhone Landscape, so now we have updated the view for iPhone in the Landscape mode only. The landscape mode will have a button more than the portrait mode.

Simulator Screen Shot Oct 27, 2015, 2.19.44 PM               Simulator Screen Shot Oct 27, 2015, 2.19.49 PM

The above images are the screenshots of iPhone 4s Portrait and landscape modes.

Changing font for iPad only

Now lets see the layout which is designed for the iPad landscape and portrait mode. this can be done when you select the wRegular – hRegular on the layout menu os size classes. We are going to change the font size of the button but just for the iPad only. When we do note that the iPads use only the wRegular hRegular for both the orientations – landscape and portrait, so the change in the button size will be visible on both the orientations.

Select any one button on the view controller, and go to the right panel on the Xcode in the properties tab of the button. You will see a ‘+’ sign just left to the font selection tab.

Screen Shot 2015-10-27 at 3.19.29 PM                       Screen Shot 2015-10-27 at 3.19.38 PM

Click it, and a menu will be open which will offer you to select some options, These are the same size layout which we saw earlier, only this time we are giving them a different font for that particular size class. Select Regular Width and the Regular Height. A new font for wR hR is just below the Font tab. Now run the project in any iPhone simulator, it should not show any changes, but stop the project and run it again selecting any iPad device, you will see that the button size has changed.

Simulator Screen Shot Oct 26, 2015, 10.17.42 AM

So this was the tutorial on what size classes are and how to use them. Hope this was useful.

iosdev
Uncategorized

So today I decided to start the blog with this first note of TOP 10 must have library to be included in your next iOS project. I wish i could have read this post before starting my next project. Anyways to cut it short below is the list of top 11 library which i would want you to use in your next project

  1. AFNetworking
    AfNetworking is one of the most popular third party library that most of the developers prefer to use. The main reason that i prefer to use AFNetworking is its easy & provides completion blocks.
  2. MBProgress HUD
    MBProgress HUD is the loading indicator which is popular amongst the developers. Again its easy on syntax and looks great :)
  3. GCDiscreetNotificationView This is very similar to android Toast message and its userfull to convey any message to user without having user interactions
  4. EGOTableViewPullRefresh
    Most of the application now use the Pull to refresh feature and if you wish to make your coding easy i will recommend to use this plugin
  5. ShareKit
    Every application will have the Share to FB, Twitter, LinkedInn functionality and you can achieve this very easily through this third party plugin. Its very popular amongst developer
  6. REFrosted Menu
    REFrosted Menu is very sweet on eyes and easy on coding part. Also customising this menu is dam easy. I will recommend this to all my fellow developers
  7. SDImageView
    For the new bee developers Image caching and loading is a big headache and this is the perfect medicine for them to recover 😛
  8. IQKeyboardManager

    IQKeyboard adds next previous buttons to the textfield automatically without writing single line of code and it will handle the scroll automatically.

  9. Action sheet Picker Control

    Action sheet picker is another easy way to load the picker view in action sheet

  10. Rating Controller

    Sometimes we need to add rating control in our project this library comes handy

  11. JDFPeekaboo

    Facebook app hides the header bar as we scroll down and shows it as we scroll up. If you need same functionality this is the library that you are looking forward.

self_sizing_cells_cell
Uncategorized

Hey Readers,

Its been quite a while since i have not written any of the blogs, and today i came across classic iOS development issues so i decided to write a blog for the same.

How to make tableview cell adopt the text height ? There are many places where we need tableview’s cell to adopt the size of the text that might be coming either from web services or from other data source. So how do we do that ?

For implementing Autosizing table view we need to follow these steps 

Step 1 : 

Set following properties on tableview

self.tableView.rowHeight = UITableViewAutomaticDimension;

Step 2 : 

Calculate height for Tableview, for this we need to take our cell’s label’s, textfields and buttons and other elements who will have dynamic heights and we need to calculate their height which is done below by calling heightNeededForText for each of the label, button, textfield and other elements.

-(CGFloat)calculaeHeightForTableViewCell:(CellArticle *)sizingCell{

    CGFloat tmpheight=[self heightNeededForText:sizingCell.txtDesc.text withFont:[UIFont fontWithName:@"Helvetica Neue" size:14.0] width:sizingCell.frame.size.width lineBreakMode:NSLineBreakByWordWrapping] + [self heightNeededForText:sizingCell.txtTitle.text withFont:[UIFont fontWithName:@"Helvetica Neue" size:14.0] width:sizingCell.frame.size.width lineBreakMode:NSLineBreakByWordWrapping];

    CGFloat tmph=MAX(tmpheight, 110);

    CGSize size = CGSizeMake(sizingCell.frame.size.width, tmph);

    NSLog(@"%f",size.height);

    return size.height + 10.0;

    

}

- (CGFloat)heightNeededForText:(NSString *)text withFont:(UIFont *)font width:(CGFloat)width lineBreakMode:(NSLineBreakMode)lineBreakMode {

    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];

                       paragraphStyle.lineBreakMode = lineBreakMode;

    CGSize size = [text boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)

                                                        options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)

                                                     attributes:@{ NSFontAttributeName: font, NSParagraphStyleAttributeName: paragraphStyle }

                                                        context:nil].size;

                       

    return ceilf(size.height);

}

Step 3 : 

Run the code and you are done.

Hope this helps.

cs1
Uncategorized

I am taking this first dive into the ocean of Blogging.

Today we will learn about using objective-c classes in Swift (also known as bridging ) in iOS. Now you will wonder what is Bridge? Bridge means interconnection between two languages. So How do we implement objective-c classes in Swift?

Step 1: Add Objective-C Implementation — .m

Add a .m file to your class, and name it CustomObject.m

Step 2: Add Bridging Header

When adding your .m file, you’ll likely be hit with a prompt that looks like this:

nakLZ

Click YES !

If you did not see the prompt, or accidentally deleted your bridging header, add a new .h file to your project and name it <#YourProjectName#>-Bridging-Header.h

In some situations, particularly when working with ObjC frameworks, you don’t add an Objective-C class explicitly and Xcode can’t find the linker. In this case, create your .h file named as mentioned above, then make sure you link its path in your target’s project settings like so:

8LiwF

Note

It’s best practice to link your project using the $(SRCROOT) macro so that if you move your project, or work on it with others using a remote repo, it will still work. $(SRCROOT) can be thought of as the directory that contains your .xcodeproj file. It might look like this:

$(SRCROOT)/Folder/Folder/<#YourProjectName#>-Bridging-Header.h

Step 3: Add Objective-C Header — .h

Add another .h file and name it CustomObject.h

Step 4: Build your Objective-C Class

In CustomObject.h

#import <Foundation/Foundation.h>

@interface CustomObject : NSObject

@property (strong, nonatomic) id someProperty;

- (void) someMethod;

@end

In CustomObject.m

#import "CustomObject.h"

@implementation CustomObject 

- (void) someMethod {
    NSLog(@"SomeMethod Ran");
}

@end

Step 5: Add Class to Bridging-Header

In YourProject-Bridging-Header.h:

#import "CustomObject.h"

Step 6: Use your Object

In SomeSwiftFile.swift:

var instanceOfCustomObject: CustomObject = CustomObject()
instanceOfCustomObject.someProperty = "Hello World"
println(instanceOfCustomObject.someProperty)
instanceOfCustomObject.someMethod()

No need to import explicitly, that’s what the bridging header is for.

So now you can dive into Swift development without worrying about if swift will support this library or not. Do drop me your suggestions how can I improvise in blogging :)