Wednesday, 17 January 2018

Swipe Delete cell from tableView (Using SQLite...)

step 1: Add following libraries.
1. libsqlite3.tbd
2. libsqlite3.0.tbd

step 2: Create Bridgeheader.h (Header) file.

step 3: Import sqlite3. Like,


#import <sqlite3.h>

step 4: Create database and table using "DB Browser For SQLite".
step 5: After create database and table, drag database_name.sqlite file and drop on your project.

step 6: Put the following code on Viewcontroller. Like,

var db : OpaquePointer? = nil
    var arr_of_Users : NSMutableArray = NSMutableArray()
    var arrData = NSMutableArray()
    var query = String()

    var temp = String()
    internal let SQLITE_STATIC = unsafeBitCast(0, to: sqlite3_destructor_type.self)
    internal let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)

step 7: Create the copy_file function. Like,

func copy_file()
    {
        let file_manager = FileManager.default
        let document_path = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
        let destination_sqlite_url = document_path.appendingPathComponent("example_db.sqlite")
        let source_sqlite_url = Bundle.main.url(forResource: "example_db", withExtension: "sqlite")
        
        print("\(destination_sqlite_url.path)")
        
        if !file_manager.fileExists(atPath: destination_sqlite_url.path)
        {
            do
            {
                try file_manager.copyItem(at: source_sqlite_url!, to: destination_sqlite_url)
                print("copied..")
                print(destination_sqlite_url.path)
            }
            catch let error as NSError
            {
                print("Enable to create database:\(error.debugDescription)")
            }
        }
        if sqlite3_open(destination_sqlite_url.path, &db) != SQLITE_OK
        {
            print("Error open database..")
        }
        else
        {
            print("Success open database..")
        }
    }


step 8: Call this function on ViewDidLoad. Like,

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

step 9: Create select query function(Get data from table). 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)")
        }
        
                while sqlite3_step(statement) == SQLITE_ROW {
            
            
            let name = sqlite3_column_text(statement, 0)
            var name_str = String()
            if name != nil
            {
                name_str = String(cString: name!)
                print("Name is=\(name_str)")
            }
            else
            {
                print("Name is not found")
            }
            
            
            
            let dict_of_user : NSMutableDictionary = NSMutableDictionary()
            dict_of_user.setObject(name_str, forKey: "name" 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 10: Call this function on viewDidLoad. Like, 

override func viewDidLoad() {
        super.viewDidLoad()
        
        copy_file()
       
        arrData = get_data_from_table("select * from example_table")
        
        
        print(arrData)

    }

Note: I already put data on database, so I will get data from database.

step 11: Create delete function. Like, 

func deleteData(_ queryStr : String) {

        var deleteStatement: OpaquePointer? = nil
        if sqlite3_prepare_v2(db, queryStr, -1, &deleteStatement, nil) == SQLITE_OK {
            if sqlite3_step(deleteStatement) == SQLITE_DONE {
                print("Successfully deleted row.")
            } else {
                print("Could not delete row.")
            }
        } else {
            print("DELETE statement could not be prepared")
        }
        
        sqlite3_finalize(deleteStatement)
    }

step 12: Create UITableView on viewcontroller. Give proper constraints on it.

step 13: Give UITableviewDatasource and UITableviewDelegate.

step 14: Put following code in NumberOfRowsInSection method. Like,

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        
        return arrData.count
    }

step 15: Put following code in cellForRowAtindexPath method. Like,

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell : custom_cell = tableView.dequeueReusableCell(withIdentifier: "custom_cell") as! custom_cell


        cell.textLabel?.text = (arrData[indexPath.row] as! NSMutableDictionary).value(forKey: "name") as? String
        return cell
    }

step 16: Put following code in commiteditingStyle method. Like,

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        
        temp = (arrData[indexPath.row] as! NSMutableDictionary).value(forKey: "name")! as! String
        print(temp)
        
        if editingStyle == .delete
        {
            
            arrData.removeObject(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .fade)

            deleteData("delete from example_table where name = '\(temp)' ")
            
        }
        
        
    }

Note: This method is use to swipe delete cell from UITableview.

Thank you...

Thursday, 4 January 2018

ios Basic interview questions.

(Note: All answers are from "www.google.co.in" and "developer.apple.com")

1. What is iphone ?
2. Types of ViewController name.
3. Diff. between Null and nil
Ans. Nil is used to represent a null pointer to an Objective-C class. NULL is used to represent a null pointer to anything else. All these, happen to have the numeric value of 0. They're all zero, but "NULL" is a void *, "nil" is an id, and "Nil" is a Class pointer.

4. Compare string.
5. Diff. between NSarray and NSmutablearray.
Ans. NSArray is immutable array. It means NSArray is static array. Value is not change. NSMutableArray is dynamic array. Means value is change in Array. 

[NSArray is an immutable Objective C class, therefore it is a reference type in Swiftand it is bridged to Array<AnyObject> . NSMutableArray is the mutable subclass ofNSArray . ... Array is a Swift construct, and generic struct, which means that it can be an array of any specific type (Int, String, AnyObject, etc.)]

6. Keyword : atomic, non-atomic, strong, retain
7. What is ARC ?
Ans. Memory management functions and its usage are handled in Swift language through Automatic reference counting (ARC). ARC is used to initialize and deinitialize the system resources thereby releasing memory spaces used by the class instances when the instances are no longer needed.

8. What is Autoreleasepool ?
Ans. At the end of the block, the autorelease pool drains, which means any pendingautorelease calls are sent as release at the end of the block. If that leads to the object reaching a 0 retain count, then it is deallocated. But whether the above is in a block or not, without ARC it is a leak.

9. Delegate method name.
10. Base class name.
11. Which type of project need to create for iphone and ipad using single code ?
12. Diff. cocoa and cocoaTouch.
13. Default framework in ios project ?
14. Diff. #define & #pragma & #import.
15. Diff. IBOutlet and IBAction.
16. What is protocol ?
Ans. protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol.

17. What are the ways to store data locally on iphone ?
18. Types of inheritance supportd.
19. Push notification.
Ans. Local and push notifications are great for keeping users informed with timely and relevant content, whether your app is running in the background or inactive. Notifications can display a message, play a distinctive sound, or update a badge on your app icon.

20. Local notification.
Ans. Local and push notifications are great for keeping users informed with timely and relevant content, whether your app is running in the background or inactive. Notifications can display a message, play a distinctive sound, or update a badge on your app icon.(https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/)

21. Post notification (add observer)
22. Database.
23. Delegate and datasource.
24. New features in latest Xcode version.
25. New features in latest ios version.
26. UIWindow, UIApplication.
27. Frameworks.
28. How to get screen size ?
29. How to get ios version ?
30. How to convert string to int ?
31. Diff. cgrect and cgpoint.
Ans. CGPoint defines coordinates in 2D space. It's composed of two CGFloats: X and Y.
CGPointMake(x, y) is a function that can be used to create a CGPoint but with Swift, you use CGPoint(x, y).
CGSize defines the dimensions a 2D object. It too is composed of two CGFloats: width and height.
Like its CGPoint alternative, CGSizeMake(width, height) is a function that can be used to create a CGSize but the shorter CGSize(width, height) exists in Swift.
The reason I mention CGSize is because CGRect is the combination of the two. It's composed of an origin (CGPoint) and a size (CGSize). It defines the coordinates and dimensions of a 2D object like a UIView. Like you may have guessed, CGRectMake(x, y, width, height) is the same as CGRect(x, y, width, height) in Swift.
(Use: https://www.reddit.com/r/swift/comments/2zy2iq/difference_between_cgpoint_cgpointmake_cgrect/)

32. Diff. UIColor and cgcolor.
33. Use of reuseIdentifire ?
34. How to button rounded ?
35. What is NSNumber ?
36. How to get particular cell ?
37. How to get rootview for an application ?
38. What is use of NSUserDefaults ?
39. Lifecycle of viewcontroller and application.
40. How to convert float value into string ?
41. Use of strong keyword with example.
42. Use of weak keyword with example.
43. Diff. NSSet and NSarray.
44. Diff. NSDictionary and NSmutabledictionary. 
45. Diff NSarray and NSDictionary.
46. Superclass of tableview.
47. Subclass of tableview.
48. Superclass of all classes.
49. What is plist, explain its content.
50. What is constraint ?
51. How to get one object from array ?
52. What is stack, queue and inheritance ?
53. Types of gestures.
54. What is struct and how its use in swift ?
55. Latest version of ios, Xcode and MACOS.
56. What is synthesize ?
57. What is GET and POST method ?
58. Which framework is use to Mapview and location ?
59. What is NSFilemanager, when and where its use ?
60. When we use facebook and social intigration in app theb types of permission is taken from the setting?
61. 5 types of UIView.
62. How to create UIViewController without storyboard ?
63. Diff. if let and guard let.
64. Types of database in ios.
65. What is storyboard ?
66. What is window ?
67. Differentiate : Not running, Inactive, Active, Background, Suspended.
68. What is Notificationcentre ?
69. Diff. delegate and notification.
70. Use of super keyword. 
71. In swift multiple inheritance supportd ?(With reason)
72. Control transfer segment. (Break, Continue, Return, Fourthrough)
73. What is NavigationController ?
74. Resolution of image in ios ?
75. What is DispatchQueue ?(Queue, Synchronous, Asynchronous)
76. Which types of back methods in navigationcontroller ?
77. Features of swift programming.
78. What is value for key and value for keypath ?
79. How to delete multiple value in array ?
80. Diff. xib and nib.
81. Why we register cell in tableview ?
82. What is contents of set ? (In scrollview, space of top and leading)