Showing posts with label IOS Tech Solutions. Show all posts
Showing posts with label IOS Tech Solutions. Show all posts

Friday, 5 February 2016

Difference between copy and mutableCopy

copy and mutableCopy are methods of NSObject Class.
copy and mutableCopy are defined in different protocols (NSCopying and NSMutableCopying, respectively), and NSArray conforms to both.

We will take the example of Array in objective-C. MutableArray is the extension of NSArray class. Therefore, all the methods available in NSArray is available in NSMutableArray, but the additional methods present in NSMutableArray is not known to NSArray class.


Now moving ahead, the copy method on an NSArray will return an object of type NSArray(The array that can not be modified). And mutableCopy method will return an object of mutable type (The array that can be modified).

Now, there can below cases :

Case 1:

    NSArray *arr1=[NSArray arrayWithObjects:@"A",@"B",@"C", nil];
    NSArray *arr2=[arr1 copy];

    NSLog(@"arr1:%@",[arr1 description]);
    NSLog(@"arr2:%@",[arr2 description]);

In this case an NSArray object is returned and is received in an NSArray object.
So, the array received can not be modified.

Therefore, we will not be able to use below statement
[arr2 insertObject:@"Z" atIndex:0];


Case 2:

    NSArray *arr1=[NSArray arrayWithObjects:@"A",@"B",@"C", nil];
    NSArray *arr2=[arr1 mutableCopy];

    NSLog(@"arr1:%@",[arr1 description]);
    NSLog(@"arr2:%@",[arr2 description]);

In this case an NSMutableArray object is returned and is received in an NSArray object.
Since the receiver object is of type NSArray, it doesn't know the methods present in NSMutableArray, arr2 will not be able to use any of the methods of NSMutableArray.
That is, the method mutableArray will make no sense in this scenario.

So, we will not be able to use below statement
[arr2 insertObject:@"Z" atIndex:0];

Case 3:

    NSArray *arr1=[NSArray arrayWithObjects:@"A",@"B",@"C", nil];
    NSMutableArray *arr2=[arr1 copy];

    NSLog(@"arr1:%@",[arr1 description]);
    NSLog(@"arr2:%@",[arr2 description]);

In this case an NSArray object is returned and is received in an NSMutableArray type object. The receiver arr2 is now pointing to an object address that is of type NSArray. However arr2 has the additional methods than NSArray, it will not be able to use those methods coz the pointed object NSArray does not know the additional methods present in arr2(NSMutableArray).

Hence, we will not be able to use below statement
[arr2 insertObject:@"Z" atIndex:0];


Case 4:

    NSArray *arr1=[NSArray arrayWithObjects:@"A",@"B",@"C", nil];
    NSMutableArray *arr2=[arr1 mutableCopy];

    NSLog(@"arr1:%@",[arr1 description]);
    NSLog(@"arr2:%@",[arr2 description]);
    [arr2 insertObject:@"Z" atIndex:0];

In this scenario, the receiver(arr2) of type NSMutableArray receives an object of type NSMutableArray. Therefore, the receiver knows the additional methods of NSMutableArray as well as the object that is being pointed by receiver(arr2).

And finally below statement will work like charm,
[arr2 insertObject:@"Z" atIndex:0];

Log before insertion will be:
arr1:(
    A,
    B,
    C
)
arr2:(
    A,
    B,
    C
)
And log after insertion will be:
arr1:(
    A,
    B,
    C
)
arr2:(
    Z,
    A,
    B,
    C
)

Monday, 2 February 2015

Objective C + Social Integration (Facebook, Twitter, Clipboard, Mail, Message, WhatsApp)

// SocialIntegration.h

#import <UIKit/UIKit.h> #import <QuartzCore/QuartzCore.h> #import <MessageUI/MessageUI.h> #import <Social/Social.h> #import <Twitter/Twitter.h> #import "WhatsAppKit.h" @interface HomeViewController : UIViewController<MFMailComposeViewControllerDelegate,MFMessageComposeViewControllerDelegate> { } -(void)openFB:(id)sender; -(void)openTW:(id)sender; -(void)copyTextIntoClipboard:(id)sender; -(void)openMail:(id)sender; -(void)openMessage:(id)sender; -(void)openWhatsApp:(id)sender; @end








// SocialIntegration.m

#define kMsgNOFbLogin @"There are no Facebook accounts configured. Please set up your Facebook account in your phone's settings." #define kMsgNOTwitterLogin @"There are no Twitter accounts configured. Please set up your Twitter account in your phone's settings." #define kError_NotSupportFeature @"Your device doesn't support this feature" // Facebook Integration - (void)openFB:(id)sender { if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) { SLComposeViewController *fbController = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook]; [fbController setInitialText:@"Text Here"]; [fbController addURL:[NSURL URLWithString:@"Url String Here"]]; UIImage *image = [UIImage imageNamed:@"logo.png"]; [fbController addImage:image]; [self presentViewController:fbController animated:YES completion:nil]; [fbController setCompletionHandler:^(SLComposeViewControllerResult result) { NSString *output; switch (result) { case SLComposeViewControllerResultCancelled: output = @"Action Cancelled"; break; case SLComposeViewControllerResultDone: output = @"Message posted to your Facebook network"; break; default: break; } [self dismissViewControllerAnimated:YES completion:nil]; //check if everythink worked properly. Give out a message on the state. [self.view makeToast:output duration:3.0 position:@"center"]; }]; } else { [self.view makeToast:kMsgNOFbLogin duration:3.0 position:@"center"]; } } // Twitter Integration -(void)openTW:(id)sender { if([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter]) { SLComposeViewController *twitterController = twitterController = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter]; [twitterController setInitialText:@"Text Here"]; [twitterController addURL:[NSURL URLWithString:@"Url String Here"]]; [self presentViewController:twitterController animated:YES completion:nil]; UIImage *image = [UIImage imageNamed:@"logo.png"]; [twitterController addImage:image]; [twitterController setCompletionHandler:^(SLComposeViewControllerResult result) { NSString *output; switch (result) { case SLComposeViewControllerResultCancelled: output = @"Action Cancelled"; break; case SLComposeViewControllerResultDone: output = @"Message posted to your Twitter network"; break; default: break; } //check if everythink worked properly. Give out a message on the state. [self.view makeToast:output duration:3.0 position:@"center"]; [self dismissViewControllerAnimated:YES completion:nil]; }]; } else { [self.view makeToast:kMsgNOTwitterLogin duration:3.0 position:@"center"]; } } //Copy Text to Clipboard -(void)copyTextIntoClipboard:(id)sender { [self trackSocialShareWithLabel:@"Clipboard"]; NSString *clipboardText = @"Text Here"; UIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; pasteboard.string = clipboardText; [self.view makeToast:@"Copied to clipboard" duration:3.0 position:@"center"]; } // Mail Integration -(void)openMail:(id)sender { if ([MFMailComposeViewController canSendMail]) { MFMailComposeViewController *mailComposeViewController = [[MFMailComposeViewController alloc] init]; mailComposeViewController.mailComposeDelegate = self; [mailComposeViewController setSubject:@"Smart Shop"]; //NSArray *toRecipients = [NSArray arrayWithObject:@""]; [mailComposeViewController setToRecipients:nil]; NSString *emailBody = [NSString stringWithFormat:@"%@\n%@",kSharedSocialString,kSharedUrlString]; [mailComposeViewController setMessageBody:emailBody isHTML:NO]; mailComposeViewController.navigationBar.barStyle = UIBarStyleBlackOpaque; [self presentViewController:mailComposeViewController animated:YES completion:nil]; } else { [self.view makeToast:kError_NotSupportFeature duration:3.0 position:@"center"]; } } #pragma mark- MFMailComposeViewControllerDelegate Method:: - (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error { [self dismissViewControllerAnimated:YES completion:nil]; } // Message Integration -(void)openMessage:(id)sender { [self trackSocialShareWithLabel:@"Message"]; if(![MFMessageComposeViewController canSendText]) { [self.view makeToast:kError_NotSupportFeature duration:3.0 position:@"center"]; return; } else { MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init]; picker.messageComposeDelegate = self; picker.recipients = nil; NSString *msgBody = [NSString stringWithFormat:@"%@\n%@",kSharedSocialString,kSharedUrlString]; picker.body = msgBody; [self presentViewController:picker animated:YES completion:nil]; } } #pragma mark- MFMessageComposeViewControllerDelegate Method:: - (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult) result { switch (result) { case MessageComposeResultCancelled: break; case MessageComposeResultFailed: { [self.view makeToast:@"Failed to send SMS!" duration:3.0 position:@"center"]; break; } case MessageComposeResultSent: break; default: break; } [self dismissViewControllerAnimated:YES completion:nil]; } // WhatsApp Integration
-(void)openWhatsApp:(id)sender { if ([WhatsAppKit isWhatsAppInstalled]) { [WhatsAppKit launchWhatsAppWithMessage:@""]; } else { [self.view makeToast:kError_NotSupportFeature duration:3.0 position:@"center"]; } }



Objective C + Parse Json From Bundle

NSMutableArray *arrayAdventureList = [self dataFromJSONFileNamed:@"Adventure"]; -(NSMutableArray *)dataFromJSONFileNamed:(NSString *)fileName { NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"json"]; NSData *fileData = [NSData dataWithContentsOfFile:filePath]; NSError *error = nil; NSMutableDictionary *dicAdventureList = [NSJSONSerialization JSONObjectWithData:fileData options:kNilOptions error:&error]; return [dicAdventureList objectForKey:@"adventure_list"]; }

Sunday, 28 December 2014

Swift + Get Height of Label Dynamically

func heightForLabel(text:String, font:UIFont, width:CGFloat) -> CGFloat
    {
        let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.max))
        label.numberOfLines = 0
        label.lineBreakMode = NSLineBreakMode.ByWordWrapping
        label.font = font
        label.text = text
        
        label.sizeToFit()
        return label.frame.height

    }




let font = UIFont(name: "Verdana", size: 12)
        var detailHeight = heightForLabel("Your String", font: font!, width: self.scrollView.bounds.size.width-10)

Thursday, 18 December 2014

Objective C + Calculate Height of Table's Cell Dynamically or At Run Time



// TableView Delegate Method
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    int width = 300; // width of your label
    
    return ([Self calculateHeightOfString:@"Your String" withFont:[UIFont systemFontOfSize:15] ofWidth:width withLineBreak:NSLineBreakByWordWrapping]+30);
    

}




// Method to calculate height
-(float)calculateHeightOfString:(NSString *)str withFont:(UIFont *)font ofWidth:(float)width withLineBreak:(NSLineBreakMode)line
{
    //NSLog(@"%s",__PRETTY_FUNCTION__);
  
CGSize suggestedSize = [str sizeWithFont:font constrainedToSize:CGSizeMake(width, FLT_MAX) lineBreakMode:line];

return suggestedSize.height;

}

Wednesday, 19 November 2014

Swift + Add UIToolbar or Done Button on Keyboard

   

  override func viewDidLoad()
    {
        super.viewDidLoad()
     
        //--- add UIToolBar on keyboard and Done button on UIToolBar ---//
        self.addDoneButtonOnKeyboard()
        

    }





    //--- *** ---//
    
    func addDoneButtonOnKeyboard()
    {
        var doneToolbar: UIToolbar = UIToolbar(frame: CGRectMake(0, 0, 320, 50))
        doneToolbar.barStyle = UIBarStyle.BlackTranslucent
       
        var flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
        var done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: Selector("doneButtonAction"))
        
        var items = NSMutableArray()
        items.addObject(flexSpace)
        items.addObject(done)
      
        doneToolbar.items = items
        doneToolbar.sizeToFit()
        
        self.textView.inputAccessoryView = doneToolbar
        self.textField.inputAccessoryView = doneToolbar
        
    }
    
    func doneButtonAction()
    {
        self.textViewDescription.resignFirstResponder()
        self.textViewDescription.resignFirstResponder()
    }

Swift + Open UIDatePicker with ActionSheet


// Compatible with iOS 7 and iOS 8 both



var datePicker: UIDatePicker!


override func viewDidLoad()
{
        super.viewDidLoad()
}



     //--- *** ---//

    func createDatePickerViewWithAlertController()
    {
        var viewDatePicker: UIView = UIView(frame: CGRectMake(0, 0, self.view.frame.size.width, 200))
        viewDatePicker.backgroundColor = UIColor.clearColor()
        
        
        self.datePicker = UIDatePicker(frame: CGRectMake(0, 0, self.view.frame.size.width, 200))
        self.datePicker.datePickerMode = UIDatePickerMode.DateAndTime
        self.datePicker.addTarget(self, action: "datePickerSelected", forControlEvents: UIControlEvents.ValueChanged)
        
        viewDatePicker.addSubview(self.datePicker)
        
        
        if(UIDevice.currentDevice().systemVersion >= "8.0")
        {

            let alertController = UIAlertController(title: nil, message: "\n\n\n\n\n\n\n\n\n\n", preferredStyle: UIAlertControllerStyle.ActionSheet)
            
            alertController.view.addSubview(viewDatePicker)
            
            
            
            
            let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel)
                { (action) in
                    // ...
            }
            
            alertController.addAction(cancelAction)
            
            let OKAction = UIAlertAction(title: "Done", style: .Default)
                { (action) in
                    
                    self. dateSelected()
             }
            
            alertController.addAction(OKAction)
            
            /*
            let destroyAction = UIAlertAction(title: "Destroy", style: .Destructive)
            { (action) in
                 println(action)
            }
            alertController.addAction(destroyAction)
            */
            
            self.presentViewController(alertController, animated: true)
            {
                    // ... 
            }

        }
        else
        {
            let actionSheet = UIActionSheet(title: "\n\n\n\n\n\n\n\n\n\n", delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: "Done")
            actionSheet.addSubview(viewDatePicker)
            actionSheet.showInView(self.view)
        }

    }


    func dateSelected()
    {
        var selectedDate: String = String()
        
        selectedDate =  Self.dateformatterDateTime(self.datePicker.date)
        
        self.textFieldFromDate.text =  selectedDate

    }


   func dateformatterDateTime(date: NSDate) -> NSString
    {
        var dateFormatter: NSDateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "MM-dd-yyyy h:mm a"
        return dateFormatter.stringFromDate(date)
    }





// Now Implement UIActionSheet Delegate Method just for support for iOS 7 not for iOS 8

    // MARK: - UIActionSheet Delegate Implementation ::
    
    func actionSheet(actionSheet: UIActionSheet!, clickedButtonAtIndex buttonIndex: Int)
    {
        switch buttonIndex
        {
            
        case 0:
            println("Done")
            self. dateSelected()
            break;
        case 1:
            println("Cancel")
            break;
        default:
            println("Default")
            break;
        }
    }


Tuesday, 11 November 2014

Swift + Save and Load Image From DocumentDirectory

var selectedImage: UIImage = "image.png"
            
  
let fileManager = NSFileManager.defaultManager()
            
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
            
var filePathToWrite = "\(paths)/SaveFile.png"
            
var imageData: NSData = UIImagePNGRepresentation(selectedImage)
            
fileManager.createFileAtPath(filePathToWrite, contents: imageData, attributes: nil)
            
var getImagePath = paths.stringByAppendingPathComponent("SaveFile.png")
            
            
            
if (fileManager.fileExistsAtPath(getImagePath))
{
       println("FILE AVAILABLE");

       //Pick Image and Use accordingly
       var imageis: UIImage = UIImage(contentsOfFile: getImagePath)!
                
       let data: NSData = UIImagePNGRepresentation(imageis)
                
}
else
{
      println("FILE NOT AVAILABLE");

}

Swift + Pick Image From Photo Library Using UIImagePickerController

First Add and Import MobileCoreServices Framework.

Confirm to UIImagePickerControllerDelegate & UINavigationControllerDelegate protocol


import UIKit

import MobileCoreServices


class ViewController: UIViewController, UIImagePickerControllerDelegate, UIAlertViewDelegate, UINavigationControllerDelegate
{

    var cameraUI: UIImagePickerController! = UIImagePickerController()
    
    
    override func viewDidLoad()
    {
        super.viewDidLoad()

    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        
    }

    //--- Take Photo from Photo Library ---//
    @IBAction func takePhotoFromPhotoLibrary(sender: AnyObject)
    {
          self.presentLibrary()
    }



    func presentLibrary()
    {
       
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)
        {
            cameraUI = UIImagePickerController()
            cameraUI.delegate = self
            cameraUI.sourceType = UIImagePickerControllerSourceType.PhotoLibrary;
            cameraUI.mediaTypes = [kUTTypeImage]
            cameraUI.allowsEditing = false
            
            self.presentViewController(cameraUI, animated: true, completion: nil)
        }
        else
        {
            // error msg

        }


    }
    
    //Mark- UIImagePickerController Delegate
    
    func imagePickerControllerDidCancel(picker:UIImagePickerController)
    {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    



    func imagePickerController(picker:UIImagePickerController!, didFinishPickingMediaWithInfo info:NSDictionary)
    {
       if(picker.sourceType == UIImagePickerControllerSourceType.PhotoLibrary)
        {
            var selectedImage: UIImage = info[UIImagePickerControllerOriginalImage] as UIImage
            
            //show Image on Image View and do other stuf that you want
            
            self.dismissViewControllerAnimated(true, completion: nil)


        }
       
    }
 


 
}  

Monday, 10 November 2014

Swift + Convert Hex Color Code to UIColor By Using Extension

In viewDidLoad


self.view.backgroundColor = UIColor(hexColorCode: "#CC1800") // Solid color

self.view.backgroundColor = UIColor(hexColorCode: "#CC1800dd") // Color with alpha





//--- Add Extension on UIColor ---//

extension UIColor
{

    convenience init(hexColorCode: String)
    {
        var red:   CGFloat = 0.0
        var green: CGFloat = 0.0
        var blue:  CGFloat = 0.0
        var alpha: CGFloat = 1.0
        
        if hexColorCode.hasPrefix("#")
        {
            let index   = advance(hexColorCode.startIndex, 1)
            let hex     = hexColorCode.substringFromIndex(index)
            let scanner = NSScanner(string: hex)
            var hexValue: CUnsignedLongLong = 0
            
            if scanner.scanHexLongLong(&hexValue)
            {
                if countElements(hex) == 6
                {
                    red   = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
                    green = CGFloat((hexValue & 0x00FF00) >> 8)  / 255.0
                    blue  = CGFloat(hexValue & 0x0000FF) / 255.0
                }
                else if countElements(hex) == 8
                {
                    red   = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
                    green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
                    blue  = CGFloat((hexValue & 0x0000FF00) >> 8)  / 255.0
                    alpha = CGFloat(hexValue & 0x000000FF)         / 255.0
                }
                else
                {
                    print("invalid hex code string, length should be 7 or 9")
                }
            }
            else
            {
                println("scan hex error")
            }
        }
        else
        {
            print("invalid hex code string, missing '#' as prefix")
        }
        
        self.init(red:red, green:green, blue:blue, alpha:alpha)
    }

}




// Other Methods

extension UIColor

{
    /**
    Create non-autoreleased color with in the given hex string and alpha
    
    :param:   hexString
    :param:   alpha
    :returns: color with the given hex string and alpha
    
    
    Example:
    
    // With hash
    let color: UIColor = UIColor(hexString: "#ff8942")
    
    // Without hash, with alpha
    let secondColor: UIColor = UIColor(hexString: "ff8942", alpha: 0.5)
    
    // Short handling
    let shortColorWithHex: UIColor = UIColor(hexString: "fff")
    
    
    */
    convenience init(hexString: String, alpha: Float)
    {
        var hex = hexString
        
        // Check for hash and remove the hash
        if hex.hasPrefix("#")
        {
            hex = hex.substringFromIndex(advance(hex.startIndex, 1))
        }
        
        // Check for string length
        assert(countElements(hex) == 6 || countElements(hex) == 3)
        
        // Deal with 3 character Hex strings
        if countElements(hex) == 3
        {
            var redHex   = hex.substringToIndex(advance(hex.startIndex, 1))
            var greenHex = hex.substringWithRange(Range<String.Index>(start: advance(hex.startIndex, 1), end: advance(hex.startIndex, 2)))
            var blueHex  = hex.substringFromIndex(advance(hex.startIndex, 2))
            
            hex = redHex + redHex + greenHex + greenHex + blueHex + blueHex
        }
        
        let redHex = hex.substringToIndex(advance(hex.startIndex, 2))
        let greenHex = hex.substringWithRange(Range<String.Index>(start: advance(hex.startIndex, 2), end: advance(hex.startIndex, 4)))
        let blueHex = hex.substringWithRange(Range<String.Index>(start: advance(hex.startIndex, 4), end: advance(hex.startIndex, 6)))
        
        var redInt:   CUnsignedInt = 0
        var greenInt: CUnsignedInt = 0
        var blueInt:  CUnsignedInt = 0
        
        NSScanner(string: redHex).scanHexInt(&redInt)
        NSScanner(string: greenHex).scanHexInt(&greenInt)
        NSScanner(string: blueHex).scanHexInt(&blueInt)
        
        self.init(red: CGFloat(redInt) / 255.0, green: CGFloat(greenInt) / 255.0, blue: CGFloat(blueInt) / 255.0, alpha: CGFloat(alpha))
    }

    
    
    /**
    Create non-autoreleased color with in the given hex value and alpha
    
    :param:   hex
    :param:   alpha
    :returns: color with the given hex value and alpha
    
    Example:
    let secondColor: UIColor = UIColor(hex: 0xff8942, alpha: 0.5)
    
    */

    convenience init(hex: Int, alpha: Float)
    {
        var hexString = NSString(format: "%2X", hex)
        self.init(hexString: hexString, alpha: alpha)
    }

}