Saturday, September 2, 2017

Unit Conversion in Swift

Unit Conversion in Swift

Here is the sample code for how to use Measurement in Swift for kg to lb (i.e. Metric to Imperial )

var weight = 20.6
var weightToBeConvert = Measurement(value: weight, unit: UnitMass.kilograms)
weightToBeConvert.convert(to: UnitMass.pounds)
weight = weightToBeConvert.value

Measurement is available from iOS10 +

Monday, February 20, 2017

Sum of array in swift 3

Sum of array in swift 3

Let's say you have array of int and you want to total of all element.
Here is example,

        let ints = 1...10 // [1,2,3,4,5,6,7,8,9,10]
        print(ints.reduce(0, +))

After running this 2 lines of code you will get total of 1 to 10.

Monday, February 13, 2017

NSDateFormatter example

NSDateFormatter example

//get current time and date
let currentTime = NSDate()
let dateFormat = NSDateFormatter()
dateFormat.dateFormat = "yyyy/MM/dd HH:mm:ss"
print(dateFormat.stringFromDate(currentTime))

here is the chart which will be the most useful date field symbols

Format Description Example
"y" A year with 1 digit. 1 AD -> "1"
42 AD -> "42"
2014 AD -> "2014"
"yy" A year with exactly 2 digits.
If less then it will padded with 0.
It will be truncated to the tens digit if larger
1 AD -> "01"
42 AD -> "42"
2014 AD -> "14"
"yyy" A year with at least 3 digits.
If less then it will padded with 0.
1 AD -> "001"
42 AD -> "042"
2014 AD -> "2014"
"yyyy" A year with at least 3 digits.
If less then it will padded with 0.
1 AD -> "0001"
42 AD -> "0042"
2014 AD -> "2014"
"M" A month with at least 1 digits. June -> "6"
December -> "12"
"MM" A month with at least 2 digits.
If less then it will padded with 0.
June -> "06"
December -> "12"
"MMM" Three letter month abbreviation June -> "Jun"
December -> "Dec"
"MMMM" Full name of month June -> "June"
December -> "December"
"MMMMM" One letter month abbreviation
January, June and July are "J"
June -> "J"
December -> "D"
"d" A day with at least 1 digit 4 -> "4"
24 -> "24"
"dd" A day with at least 2 digit.
If less then it will padded with 0.
4 -> "04"
24 -> "24"
"E","EE" or "EEE" 3 letter day abbreviation of day name Wednesday -> "Wed"
Thursday -> "Thu"
"EEEE" Full day name Wednesday -> "Wednesday"
Thursday -> "Thursday"
"EEEEE" 1 letter day abbreviation of day name.
Teusday and Thursday are "T"
Wednesday -> "W"
Thursday -> "T"
"EEEEEE" 2 letter day abbreviation of day name Wednesday -> "We"
Thursday -> "Th"
"a" period of day (AM/PM) 7 PM -> "PM"
10 AM -> "AM"
"h" 12 hour based with at least 1 digit 7 PM -> "7"
10 AM -> "10"
"hh" 12 hour based with at least 2 digit.
If less then it will padded with 0.
7 PM -> "07"
10 AM -> "10"
"H" 24 hour based with at least 1 digit 7 PM -> "19"
10 AM -> "10"
"HH" 24 hour based with at least 2 digit.
If less then it will padded with 0.
7 PM -> "19"
9 AM -> "09"
"m" A minute with at least 1 digit 40 -> "40"
1 -> "1"
"mm" A minute with at least 2 digit.
If less then it will padded with 0.
40 -> "40"
1 -> "01"
"s" A second with at least 1 digit 40 -> "40"
1 -> "1"
"ss" A second with at least 2 digit.
If less then it will padded with 0.
40 -> "40"
1 -> "01"
"S" A tenth place of fraction second 123 ms -> "1"
7 ms -> "0"
"SS" A tenth and hundredths place of fractions second 123 ms -> "12"
7 ms -> "00"
"SSS" A tenth, hundredths and thousandths place of fractions second 123 ms -> "123"
7 ms -> "007"

Thursday, January 28, 2016

MFMessageComposeViewControllerDelegate not working

MFMessageComposeViewControllerDelegate not working

Steps to work with MFMessageComposeViewController.

1. Create object of MFMessageComposeViewController class.

let messageController = MFMessageComposeViewController()

2. Setting value to object

messageController.body = message // message is String object
messageController.recipients = recipients // recipients is Array of number

3. Setting delegate of object

messageController.messageComposeDelegate = self
//messageController.delegate = self
//Above commented statement is not correct. If you used that in your code then you will never be able to return in to your app

4. Present message controller

presentViewController(messageController, animated: true, completion: { () -> Void in
                    // completion Block
                })

5. Handle delegate

//MARK: - MFMessageComposeViewControllerDelegate
    func messageComposeViewController(controller: MFMessageComposeViewController, didFinishWithResult result: MessageComposeResult) {
switch (result) {
        case MessageComposeResultCancelled:
            print("Message was cancelled")
            self.dismissViewControllerAnimated(true, completion: nil)
        case MessageComposeResultFailed:
            print("Message failed")
            self.dismissViewControllerAnimated(true, completion: nil)
        case MessageComposeResultSent:
            print("Message was sent")
            self.dismissViewControllerAnimated(true, completion: nil)
        default:
            break;
        }
}

It will work like charm.
Please use messageController.messageComposeDelegate = self for setting delegate and that will work perfect.

Wednesday, January 13, 2016

Remove notification observer and close DB connection in swift

Remove notification observer and close DB connection in swift

Which is the proper method to remove notification observer or close Database connection?

Earlier we was calling 'ViewDidUnload' method for this kind of purpose.

But now it is not possible.
According to Swift Book there is deinit block.
Which is going to call immediately before a class instance is deallocated.

Remember here, deinit is not method.


e.g.
deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

Friday, September 11, 2015

BITCODE error/warning in iOS 9 Xcode 7

BITCODE error/warning in iOS 9 Xcode 7

Today I got the error of BITCODE in project.
After some searching I became to knew that yesterday I upgrade my Xcode from 6.4 to 7 beta 5.

detail of error is as below


ld: '/Users/Mrugesh/Documents/NewApp/NewApp/Fabric.framework/Fabric(Fabric.o)' does not contain bitcode. You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE), obtain an updated library from the vendor, or disable bitcode for this target. for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

The error says that i used Fabric framework which was not build with bitcode and new Xcode requires that.
So the solution is that either we have to use framework which build with bitcode or just disable bitcode from project setting for desired target like me.

Project setting > target > Build setting > Build Options > Enable Bitcode > NO

And problem solved.

Another problem I faced yesterday was that I was fetching data from API and for that I was using http URL instead of https.  And It stops send request.
For that I added dictionary to info.plist which is as below.

Wednesday, August 19, 2015

working with UIMenuController

working with UIMenuController

I am creating menu on longPressGesture of some view.
The code is as below.

- (void)showMenu:(UILongPressGestureRecognizer *)gestureRecognizer
{
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan) {
        
        [self becomeFirstResponder];

        /*
         Set up th menu.
         */
        UIMenuItem *menuItem1 = [[UIMenuItem alloc] initWithTitle:@"Item 1" action:@selector(item1Selected:)];
        UIMenuItem *menuItem2 = [[UIMenuItem alloc] initWithTitle:@"Item 2" action:@selector(item2Selected:)];

        UIMenuController *menuController = [UIMenuController sharedMenuController];
        [menuController setMenuItems:@[menuItem1,menuItem2]];
        
        CGPoint location = [gestureRecognizer locationInView:[gestureRecognizer view]];
        CGRect menuLocation = CGRectMake(location.x, location.y, 0, 0);
        [menuController setTargetRect:menuLocation inView:[gestureRecognizer view]];
        
        [menuController setMenuVisible:YES animated:YES];
    }

}

- (void)item1Selected:(UIMenuController *)controller
{
    NSLog("Item 1 Selected");
}

- (void)item2Selected:(UIMenuController *)controller
{
    NSLog("Item 2 Selected");
}

// UIMenuController requires that we can become first responder or it won't display
- (BOOL)canBecomeFirstResponder
{
    return YES;
}