Monday 11 December 2017

Data Model



1. Model Class


class TestModel{
    
    var name : String!
    var age : String!
    
    init(name : String!, age : String!) {
        self.name = name
        self.age = age
    }   

}

2. View Controller


import UIKit

class ViewController: UIViewController {

  
    @IBOutlet weak var name: UITextField!
    @IBOutlet weak var age: UITextField!
    
    @IBOutlet weak var nameLbl: UILabel!
    @IBOutlet weak var ageLbl: UILabel!
    
    var SavedData : TestModel!
    
    override func viewDidLoad() {
        super.viewDidLoad()

      
        
    }
    
    @IBAction func saveData(_ sender: Any) {
        let vName : String = name.text!
        let vAge : String = age.text!
        
         SavedData = TestModel(name: vName, age: vAge)
        print(SavedData.name)
        
        
    }
    
    
    @IBAction func showData(_ sender: Any) {
        
        nameLbl.text = SavedData.name
        ageLbl.text = SavedData.age
    }

}

Saturday 9 December 2017

Webkit




1. Drag Webkit View to Storyboard ViewController

2. Below code -


import UIKit
import WebKit

class ViewController: UIViewController {

    
    @IBOutlet weak var mywebview: WKWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        let url = NSURL(string:"http://www.appcoda.com")
        let request = URLRequest(url: url as! URL)
        mywebview.load(request)
    }


}

Visual Effect with Blur Effect






1. Place imageview in viewcontroller ans set image

2. Create IBOutlet

Here is complete code -



import UIKit
import AVKit

class ViewController: UIViewController {

    
    @IBOutlet weak var myImage: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()

        
    }
    
    override func viewDidAppear(_ animated: Bool) {
  
        myImage.addBlurEffect()
    }
}

extension UIImageView
{
    func addBlurEffect()
    {
        let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        blurEffectView.frame = self.bounds
        
        blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] // for supporting device rotation
        self.addSubview(blurEffectView)
    }

}

AVKit Player


First, Allow Internet perission in info.plist

Info.plist -> Add (+) -> App Transport Security Setting -> Add(+) ->
Allow Arbitary Load -> YES



1. Dynamic create AVPlayer - Just normal player

------------------------------------------------------
let videoURL = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
        let player = AVPlayer(url: videoURL!)
        let playerLayer = AVPlayerLayer(player: player)
        playerLayer.frame = self.view.bounds
        self.view.layer.addSublayer(playerLayer)

        player.play()
------------------------------------------------------

2. Dynamic create AVPlayerViewController - With full functionality (Play, Stop, Mute)

------------------------------------------------------
let videoURL = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
        let player = AVPlayer(url: videoURL!)
        let playerViewController = AVPlayerViewController()
        playerViewController.player = player
        self.present(playerViewController, animated: true) {
            playerViewController.player!.play()

        }
------------------------------------------------------



22

Monday 20 November 2017

Custom Activity Indicator



//
//  ViewController.swift
//  MyFirstApp
//
//  Created by Divakar on 19/10/17.
//  Copyright © 2017 Divakar. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        customActivityIndicatory(self.view, startAnimate: true)
        
        //hide activityIndicatorView
     //   customActivityIndicatory(self.view, startAnimate: false)
    }

    
    
    @discardableResult
    func customActivityIndicatory(_ viewContainer: UIView, startAnimate:Bool? = true) -> UIActivityIndicatorView {
        let mainContainer: UIView = UIView(frame: viewContainer.frame)
        mainContainer.center = viewContainer.center
        mainContainer.backgroundColor = hexStringToUIColor(hex: "#FFFFFF")
        mainContainer.alpha = 0.5
        mainContainer.tag = 789456123
        mainContainer.isUserInteractionEnabled = false
        
        let viewBackgroundLoading: UIView = UIView(frame: CGRect(x:0,y: 0,width: 80,height: 80))
        viewBackgroundLoading.center = viewContainer.center
        viewBackgroundLoading.backgroundColor = hexStringToUIColor(hex: "#444444")
        viewBackgroundLoading.alpha = 0.5
        viewBackgroundLoading.clipsToBounds = true
        viewBackgroundLoading.layer.cornerRadius = 15
        
        let activityIndicatorView: UIActivityIndicatorView = UIActivityIndicatorView()
        activityIndicatorView.frame = CGRect(x:0.0,y: 0.0,width: 40.0, height: 40.0)
        activityIndicatorView.activityIndicatorViewStyle =
            UIActivityIndicatorViewStyle.whiteLarge
        activityIndicatorView.center = CGPoint(x: viewBackgroundLoading.frame.size.width / 2, y: viewBackgroundLoading.frame.size.height / 2)
        if startAnimate!{
            viewBackgroundLoading.addSubview(activityIndicatorView)
            mainContainer.addSubview(viewBackgroundLoading)
            viewContainer.addSubview(mainContainer)
            activityIndicatorView.startAnimating()
        }else{
            for subview in viewContainer.subviews{
                if subview.tag == 789456123{
                    subview.removeFromSuperview()
                }
            }
        }
        return activityIndicatorView
    }

        func hexStringToUIColor (hex:String) -> UIColor {
            var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
    
            if (cString.hasPrefix("#")) {
                cString.remove(at: cString.startIndex)
            }
    
            if ((cString.characters.count) != 6) {
                return UIColor.gray
            }
    
            var rgbValue:UInt32 = 0
            Scanner(string: cString).scanHexInt32(&rgbValue)
    
            return UIColor(
                red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
                green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
                blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
                alpha: CGFloat(1.0)
            )
        }
}


Saturday 18 November 2017

Homebrew and Carthage Intallation




Homebrew and Carthage Intallation 


To install Carthage and create Cartfile, Follow below step - 

A. Install Homebrew

Website :  https://brew.sh
  1. Open terminal
  2. Paste below code and enter - Command  :  /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
  3. Enter, wait for while

B. Install Carthage
  1. Download the latest “Carthage.pkg” from this website : https://github.com/Carthage/Carthage/releases, ( In my case - 0.26.2 )
  2. Double-click Carthage.pkg to run the installer
  3. Click Continue, select a location to install to, click Continue again, and finally click Install

Note : When you attempt to run the installer, you may see a message stating “Carthage.pkg can’t be opened because it is from an unidentified developer.” If so, Control-click the installer and choose Open from the context menu.

C. Check Carthage Version
  1. Open Terminal & Hit this command - carthage version

D. Creating First Cartfile

A Cartfile is a simple text file that describes your project’s dependencies to Carthage, so it can determine what to install. Each line in a Cartfile states where to fetch a dependency from, the name of the dependency, and optionally, which version of the dependency to use. A Cartfile is the equivalent of a CocoaPods Podfile.
Navigate to the root directory of your project in Terminal (the directory that contains your .xcodeproj file) using the cd command:

cd ~/Path/To/Starter/Project

Create an empty Cartfile with the touch command:

touch Cartfile

And then open the file up in Xcode for editing:

open -a Xcode Cartfile

If you’re familiar with another text editor, like Vim, then feel free to use that instead. Don’t, however, use TextEdit to edit the file; with TextEdit it’s too easy to accidentally use so-called “smart quotes” instead of straight quotes, and they will confuse Carthage.
Add the following lines to the Cartfile and save it:
github "Alamofire/Alamofire" == 4.5
github "Alamofire/AlamofireImage" ~> 3.2
These two lines tell Carthage that your project requires Alamofire version 4.5, and the latest version of AlamofireImage that’s compatible with version 3.2.





/////
 FOR SOCKET
Carthage
Add this line to your Cartfile:
github "socketio/socket.io-client-swift" ~> 13.0.0
Run carthage update --platform ios,macosx.
Add the Starscream and SocketIO frameworks to your projects and follow the usual Carthage process.
CocoaPods 1.0.0 or later
Create Podfile and add pod 'Socket.IO-Client-Swift':
use_frameworks!

target 'YourApp' do
    pod 'Socket.IO-Client-Swift', '~> 13.0.0'
end
Install pods:
$ pod install
Import the module:
Swift:
import SocketIO
Objective-C:
@import SocketIO;


Summary

1. Copy path pf your project

cd ~/Path/To/Starter/Project

2. Create an empty Cartfile with the touch command:

touch Cartfile

3. And then open the file up in Xcode for editing:

open -a Xcode Cartfile

4. Add the following lines to the Cartfile and save it:


add cart file like - github "Alamofire/Alamofire" == 4.5

5. Now, Install Carthage

carthage update --platform ios,macosx


Wednesday 15 November 2017

AlertDialog with Textfield








*****

let alertController = UIAlertController(title: "Your Title", message: "Your Subtitle here", preferredStyle: UIAlertControllerStyle.alert)
        
        alertController.addTextField(configurationHandler: nil)
        
        let OKAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (action) -> Void in
            
        }
        
        alertController.addAction(OKAction)

        present(alertController, animated: true, completion: nil)

******

       // IF DATA NULL, CALL YOUR METHOD


//        let OKAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (action) -> Void in
//            let textfield = alertController.textFields![0]
//            if textfield.text?.characters.count == 0 {
//
//              //  self.askForNickname()
//            }
//            else {
//

//            }

Monday 13 November 2017

Passing Data using Struct in between controller or method








We can pass value using "struct" in swift 3
  1. Create a swift file in your project
  2. Create a class in the swift file created like bellow
        class StructOperation {
          struct glovalVariable {
          static var userName = String();
         }
     }
  3. Assing value to "static var userName" variable of " struct glovalVariable" in "StructOperation" class from First View Controller like
     @IBAction func btnSend(_ sender: Any) {
        StructOperation.glovalVariable.userName = "Enamul Haque";
       //Code Move to Sencon View Controller
     }
  4. In destination view controller get value like bellow
     var username = StructOperation.glovalVariable.userName;



Monday 18 September 2017

UITableView With Checkbox





import UIKit

class GroupsListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
      
    let groupListNames = ["Group-1", "Group-2", "Group-3", "Group-4", "Group-5", "Group-6"]
 /*   let groupListNames = ["Group-1", "Group-2", "Group-3", "Group-4", "Group-5", "Group-6", "Group-7", "Group-8","Group-9", "Group-10", "Group-11", "Group-12"]*/
     var count : UInt = 0

    
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        
        return groupListNames.count
    }
   
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
   
         if(tableView.cellForRow(at: indexPath)?.accessoryType == UITableViewCellAccessoryType.checkmark){
            tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.none

            img2 = UIImageView()
            img2.sizeToFit()
            img2.frame = CGRect(x: 10, y: 10, width: 24, height: 24)
            img2.image = UIImage(named: "UnSelectedIcon.png")
            img2.contentMode = UIViewContentMode.scaleAspectFit
            tableView.cellForRow(at: indexPath)?.accessoryView = img2
            tableView.cellForRow(at: indexPath)?.backgroundColor = UIColor.clear

         }else{
            tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.checkmark
            img1 = UIImageView()
            img1.sizeToFit()
            img1.frame = CGRect(x: 10, y: 10, width: 24, height: 24)
            img1.image = UIImage(named: "SelectedIcon.png")
            img1.contentMode = UIViewContentMode.scaleAspectFit
            tableView.cellForRow(at: indexPath)?.accessoryView = img1
            tableView.cellForRow(at: indexPath)?.backgroundColor = UIColor.clear
   
         }
    }

    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! GroupListsTableViewCell
        cell.GroupNameLabel.text = groupListNames[indexPath.row]
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if count < 11 {
        img2 = UIImageView()
        img2.sizeToFit()
        img2.frame = CGRect(x: 10, y: 10, width: 24, height: 24)
        img2.image = UIImage(named: "UnSelectedIcon.png")
        img2.contentMode = UIViewContentMode.scaleAspectFit
        cell.accessoryView = img2
        cell.backgroundColor = UIColor.clear
           count  = count + 1
        }
    }

    
   
    
    var img1 :UIImageView!
    var img2 :UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
    
    }
    
  /*  @IBAction func funcGotoMyProfileVC(_ sender: Any) {
        self.view.endEditing(true)
        let signUpVC = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController")
        self.navigationController?.pushViewController(signUpVC!, animated: false)
    }*/
    
    @IBAction func funcGotoLoginVC(_ sender: Any) {
        self.view.endEditing(true)
        let signUpVC = self.storyboard?.instantiateViewController(withIdentifier: "AddJobViewController")
        self.navigationController?.pushViewController(signUpVC!, animated: false)
    }

}

NaOpen another controller







import UIKit

class ViewController : UIViewController{
    
    override func viewDidLoad() {
        super.viewDidLoad()
   
        
    }
    
  
    
    @IBAction func funcGotoGroupListVC(_ sender: Any) {
        self.view.endEditing(true)
        let signUpVC = self.storyboard?.instantiateViewController(withIdentifier: "GroupsListViewController")
        self.navigationController?.pushViewController(signUpVC!, animated: false)

    }
}

Hide Keyboard




import UIKit

class ViewController : UIViewController{
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action:  #selector(self.dismissKeyboard))
        view.addGestureRecognizer(tap)
        
    }
    
    func dismissKeyboard() {
        view.endEditing(true)
    }
}