Monday, 25 December 2017

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...

No comments:

Post a Comment