Thursday, 28 December 2017

CollectionView With Header and Footer

step 1: Put CollectionView on ViewController and give constraints.
step 2: Create cocoatouch class UICollectionviewcell with .xib file.
step 3: Define the cell in ViewController. Like,


@IBOutlet var collection_View: UICollectionView!
    override func viewDidLoad() {
        super.viewDidLoad()
          
        self.collection_View.register(UINib(nibName: "collection_cell", bundle: nil), forCellWithReuseIdentifier: "collection_cell")
      
        // Do any additional setup after loading the view, typically from a nib.
    }

step 4: Give UICollectionviewDataSource and UICollectionviewDelegate. Like,

class ViewController: UIViewController, UICollectionViewDataSource,UICollectionViewDelegate

step 5: Put the following code on given Datasource method. Like,

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 25
    }

step 6: Put the following code on given Datasource method. Like,

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell : collection_cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collection_cell", for: indexPath) as! collection_cell
        cell.update_Data(strValue: "\(indexPath.item)")
        return cell
    }

(Note: "update_Data" is function, it is define in "collection_cell" class. Like,)

class collection_cell: UICollectionViewCell {

    @IBOutlet var lbl_cell_value: UILabel!
    override func awakeFromNib() {
        super.awakeFromNib()
       
        // Initialization code
    }
    
    func update_Data(strValue : String) {
        lbl_cell_value.text = strValue
    }

}

step 7: Give the size of particular section. Like,

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        //        let height = collectionView.frame.size.height
        //        let width  = collectionView.frame.size.width
        let width = (UIScreen.main.bounds.size.width-10)/3
        
        return CGSize(width: CGFloat(width), height: CGFloat(width))
    }

step 8: Create header and footer for UICollectionView...

Create UICollectionReusableView file with .xib. And put UILabel on the xib with proper constraints.

In viewcontroller, register header and footer collectionReusableview. Like,

class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {

    @IBOutlet var clView: UICollectionView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
     
        self.clView.register(UINib(nibName: "HeaderCollectionReusableView", bundle: Bundle.main), forSupplementaryViewOfKind:UICollectionElementKindSectionHeader, withReuseIdentifier: "HeaderCollectionReusableView")

        self.clView.register(UINib(nibName: "FooterCollectionReusableView", bundle: Bundle.main), forSupplementaryViewOfKind:UICollectionElementKindSectionFooter, withReuseIdentifier: "FooterCollectionReusableView")
        
    }

step 9: put UICollectionViewDelegateFlowLayout method and put following code in that method. Like,

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        if kind == UICollectionElementKindSectionHeader {
            
            let header : HeaderCollectionReusableView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HeaderCollectionReusableView", for: indexPath) as! HeaderCollectionReusableView
            return header
            
            
            
        }else if kind == UICollectionElementKindSectionFooter {
            let header : FooterCollectionReusableView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "FooterCollectionReusableView", for: indexPath) as! FooterCollectionReusableView
            return header

        }
        
        return UICollectionReusableView()
    }

Thank you...

Download image from JSON(Using SDWebImage and Without use SDWebImage)

Using SDWebImage:-

step 1: Install pods of SDWebImage and import DSWebImage in your viewController.
step 2: You can call and display JSON data using Alamofire / JSONSerialization.
step 3: If you are use UITableviewcontroller, than in CellForRowAtIndexPath put this code. Like,

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell : TableViewCell_json = tableView.dequeueReusableCell(withIdentifier: "TableViewCell_json") as! TableViewCell_json
        
        let arr = (json_Data["hits"] as! NSArray)
        let temp_dict = (arr[indexPath.row] as! [String:AnyObject])

            cell.lbl_value.text = String((describing: temp_dict["id"] as? Int) ?? 0)
        
        cell.img_pic.sd_setImage(with: URL(string: ((self.json_Data["hits"] as! NSArray).object(at: indexPath.row) as! NSDictionary)["previewURL"] as! String), placeholderImage: #imageLiteral(resourceName: "cool-wild-animal-wallpaper-high-quality-For-Desktop-Wallpaper"), options: SDWebImageOptions.cacheMemoryOnly, completed: nil)
        
        return cell

    }

Without using SDWebImage:-

step 1: You can call and display JSON data using Alamofire / JSONSerialization.
step 2: If you are use UITableviewcontroller, than in CellForRowAtIndexPath put this code. Like,

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell : TableViewCell_json = tableView.dequeueReusableCell(withIdentifier: "TableViewCell_json") as! TableViewCell_json
        
        //Get Image from URL...
        let image_url = URL(string: ((self.json_Data["hits"] as! NSArray).object(at: indexPath.row) as! NSDictionary)["previewURL"] as! String)
        
        let session = URLSession(configuration: .default)
        let download_pic = session.dataTask(with: image_url!)
        {
            (data, responce, error) in
            if let e = error
            {
                print("Error download picture\(e)")
            }
            else
            {
                if let res = responce as? HTTPURLResponse
                {
                    print("Downloaded picture responce code\(res.statusCode)")
                    
                    if let image_data = data
                    {
                        let img_1 = UIImage(data: image_data)
                        
                        cell.img_pic.image = img_1
                    }
                    else
                    {
                        print("Could not get image")
                    }
                }
                else
                {
                    print("Could not get image code")
                }
            }
        }
        download_pic.resume()
        

        return cell

    }

Thank you...

Monday, 25 December 2017

UIDatePickerView Demo

Note : When user click on UITextfield, UIDatePicker is open.

step 1: Put UITextfield and give their IBOutlet and textfielddelegate.
step 2 : In ViewController, create variable of UIDatepicker. Like,


var date_1 = UIDatePicker()

step 3: Create function with argument. Like,

func pick_Date(_ textfield : UITextField) {
        //For create date picker...
        self.date_1 = UIDatePicker(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 215))
        self.date_1.backgroundColor = UIColor.white
        lf.date_1.datePickerMode = .date
        self.txt_select_date.inputView = date_1
        
        //for create toolbar...
        let toolbar = UIToolbar()
        toolbar.barStyle = .default
        toolbar.isTranslucent = true
        toolbar.tintColor = UIColor(red: 90/255, green: 215/255, blue: 255/255, alpha: 1)
        toolbar.sizeToFit()
        
        //Add button toolbar...
        let btn_add = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(Date_ViewController.click_Done))
        let btn_space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let btn_cancel = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(Date_ViewController.click_Cancel))
        toolbar.setItems([btn_add, btn_space, btn_cancel], animated: true)
        toolbar.isUserInteractionEnabled = true
        txt_select_date.inputAccessoryView = toolbar
    }

step 4: Create done button and cancel button item function. Like,

func click_Done() {
        let date_Formatter = DateFormatter()
        date_Formatter.dateStyle = .medium
        date_Formatter.timeStyle = .none
        txt_select_date.text = date_Formatter.string(from: date_1.date)
        txt_select_date.resignFirstResponder()
    }
    
    func click_Cancel() {
        txt_select_date.resignFirstResponder()
    }

step 5: Call "pic_date" function on textfieldDidBeginEditing delegate method. Like,

func textFieldDidBeginEditing(_ textField: UITextField) {
        self.pick_Date(self.txt_select_date)
    }

Thank you...

Alamofire API with SQLite Database

Note : Call the API using alamofire. Fetch the data from the API and display in UITextfield. When user click on UIButton than those data is store on SQLite database.

step 1: Install pods.
step 2: In ViewController, put 3 UITextfields and UIButton.
step 3: Give IBOutlets and delegate of UITextfield and give IBAction of UIButton.
step 4: Create function of get the data from API. Like,


var json_data : NSDictionary = NSDictionary()
func get_call_API_Alamofire() {
        
        Alamofire.request("URL", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in
            if response.error == nil {
                
                self.json_data = response.value as! NSDictionary
                print("JSON Alamofire Data:",self.json_data)
                
                self.txt_id.text = String(describing: (((self.json_data.value(forKey: "hits") as! NSArray).object(at: 0) as! NSDictionary).value(forKey: "user_id") as! Int))
                
                self.txt_user.text = (((self.json_data.value(forKey: "hits") as! NSArray).object(at: 0) as! NSDictionary).value(forKey: "user") as! String
                )
                
                self.txt_tag.text = (((self.json_data.value(forKey: "hits") as! NSArray).object(at: 0) as! NSDictionary).value(forKey: "tags") as! String
                )

            }
            else
            {
                print("Error=",response.error!.localizedDescription)
            }
        }
        

    }

step 5: Call the function in ViewDidLoad. Like,

override func viewDidLoad() {
        super.viewDidLoad()
        
        get_call_API_Alamofire()
        
        // Do any additional setup after loading the view, typically from a nib.
    }

Note : When data is print, your code is perfect upto here.

step 6: Now, Add following libraries.
1. libsqlite3.tbd
2. libsqlite3.0.tbd

step 7: Create Bridgeheader.h (Header) file.
step 8: Import sqlite3. Like,

#import <sqlite3.h>

step 9: Create database and table using "DB Browser For SQLite".
step 10: After create database and table, drag database_name.sqlite file and drop on your project.
step 11: Give the Bridgeheader.h file path in "Build Setting".
step 12: Create copy_file function on ViewController. Like,

var db: OpaquePointer? = nil
    internal let SQLITE_STATIC = unsafeBitCast(0, to: sqlite3_destructor_type.self)
    internal let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)

func copyFile()
    {
        let fileManager = FileManager.default
        let documentsPath = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
        let destinationSqliteURL = documentsPath.appendingPathComponent("photo_db.sqlite")
        let sourceSqliteURL = Bundle.main.url(forResource: "photo_db", withExtension: "sqlite")
        print("\(destinationSqliteURL.path)")
        if !fileManager.fileExists(atPath: destinationSqliteURL.path) {
            // var error:NSError? = nil
            do {
                try fileManager.copyItem(at: sourceSqliteURL!, to: destinationSqliteURL)
                print("Copied")
                print(destinationSqliteURL.path)
            } catch let error as NSError {
                print("Unable to create database \(error.debugDescription)")
            }
        }
        
        
        if sqlite3_open(destinationSqliteURL.path, &db) != SQLITE_OK {
            print("error opening database")
        }
        else{
            print("success opening database")
        }
    }

step 13: Call the function in ViewDidLoad. Like,

override func viewDidLoad() {
        super.viewDidLoad()
        
        get_call_API_Alamofire()
        copyFile()
        
        // Do any additional setup after loading the view, typically from a nib.
    }

step 14: Create get_data_from_table function in ViewController. Like,

func get_data_from_table(_ querySQL : String) -> NSMutableArray {
        var statement : OpaquePointer? = nil
        
        if sqlite3_prepare_v2(db, querySQL, -1, &statement, nil) != SQLITE_OK
        {
            let error_msg = String(cString: sqlite3_errmsg(db))
            print("Error prepaer select:\(error_msg)")
        }
        
        let arr_of_Users : NSMutableArray = NSMutableArray()
        while sqlite3_step(statement) == SQLITE_ROW {
            
            
            let user_id = sqlite3_column_text(statement, 0)
            var user_id_str = String()
            if user_id != nil
            {
                user_id_str = String(cString: user_id!)
                print("User id is=\(user_id_str)")
            }
            else
            {
                print("User id is not found")
            }
            
            let user_name = sqlite3_column_text(statement, 1)
            var user_name_str = String()
            if user_name != nil
            {
                user_name_str = String(cString: user_name!)
                print("User name is=\(user_name)")
            }
            else
            {
                print("User name is not found")
            }
            
            let user_tags = sqlite3_column_text(statement, 1)
            var user_tags_str = String()
            if user_tags != nil
            {
                user_tags_str = String(cString: user_name!)
                print("User tags are=\(user_tags)")
            }
            else
            {
                print("User tags are not found")
            }
            
            let dict_of_user : NSMutableDictionary = NSMutableDictionary()
            dict_of_user.setObject(user_id_str, forKey: "user_id" as NSCopying)
            dict_of_user.setObject(user_name_str, forKey: "user_name" as NSCopying)
            dict_of_user.setObject(user_tags_str, forKey: "user_tags" as NSCopying)
            
            arr_of_Users.add(dict_of_user)
        }
        print(arr_of_Users)
        
        if sqlite3_finalize(statement) != SQLITE_OK
        {
            let err_msg = String(cString: sqlite3_errmsg(db))
            print("Error finalized prepared statement\(err_msg)")
        }
        statement = nil
        return arr_of_Users
    }

step 15: Call the function in ViewDidLoad. Like,

override func viewDidLoad() {
        super.viewDidLoad()
        
        get_call_API_Alamofire()    //Get and print the data from API...
        copyFile()                  //Copy the .sqlite file...
        get_data_from_table("select * from store_data") //Display the data from SQLite table using select query...
        // Do any additional setup after loading the view, typically from a nib.
    }

step 16: Create Insert data function in ViewController. Like,

func insert_data(_ queryStr : String
{
        var statement : OpaquePointer? = nil
        if sqlite3_prepare_v2(db, queryStr, -1, &statement, nil) != SQLITE_OK    
        {
            let error_msg = String(cString: sqlite3_errmsg(db))
            print("error preparing insert\(error_msg)")
        }
        if sqlite3_step(statement) != SQLITE_DONE {
            let error_msg = String(cString: sqlite3_errmsg(db))
            print("failure inserting foo\(error_msg)")
        }
        else
        {
            print("successfully inserted..")
        }
}

step 17: Call this function in IBAction of UIButton. Like,

@IBAction func btn_click(_ sender: UIButton) {
        let dict : NSMutableDictionary = NSMutableDictionary()
        
        dict.setObject(self.txt_id.text ?? String(), forKey: "user_id" as NSCopying)
        dict.setObject(self.txt_user.text ?? String(), forKey: "user_name" as NSCopying)
        dict.setObject(self.txt_tag.text ?? String(), forKey: "user_tags" as NSCopying)
        
        let string_data = "insert into store_data (user_id,user_name,user_tags) values ('\(dict.value(forKey: "user_id")!)','\(dict.value(forKey: "user_name")!)','\(dict.value(forKey: "user_tags")!)')"
        
        insert_data(string_data)
    }

Thank you...