Showing posts with label swift. Show all posts
Showing posts with label swift. Show all posts

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.

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)
    }

Monday, November 10, 2014

Image Loading and Caching

Image Loading and Caching


var imageCache = [String : UIImage]()


var image = self.imageCache[urlString]
       
       
        if( image == nil ) {
            // If the image does not exist, we need to download it
            var imgURL: NSURL = NSURL(string: urlString)
           
            // Download an NSData representation of the image at the URL
            let request: NSURLRequest = NSURLRequest(URL: imgURL)
            NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
                if error == nil {
                    image = UIImage(data: data)
                   
                    // Store the image in to our cache
                    self.imageCache[urlString] = image
                    dispatch_async(dispatch_get_main_queue(), {
                        if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) {
                            cellToUpdate.imageView?.image = image
                        }
                    })
                }
                else {
                    println("Error: \(error.localizedDescription)")
                }
            })
           
        }
        else {
            dispatch_async(dispatch_get_main_queue(), {
                if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) {
                    cellToUpdate.imageView?.image = image
                }
            })
        }



NOTE:This is in swift programming.