Powered By Blogger

Thursday, March 16, 2017

How to integrate "SwiftLint" library into XCode project ?


Hi everyone,

Now a days, I was looking for a tool which can assist the developers to write code with good quality by following some basic standards. A tool which can throws warnings/errors if developer is not following the code writing rules. I have found multiple tools for multiple platforms. But I have chosen "SwiftLint" for "SWIFT" language, which is the same as its prior version "OCLint" for "Objective C".

A) Steps to integrate :



Please read this article's contents carefully to integrate it successfully and below are the steps :

Step 1 : Install ‘Homebrew’ into your Mac using the below command :

a. /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Step 2 : Install ‘SwiftLint’ package with the help of below command :

a. brew install swiftlint

Step 3 : To Integrate SwiftLint into current Xcode Project, add a new “Run Script” in Build phase with below contents :

if which swiftlint >/dev/null; then
swiftlint
else
echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"
fi

Note 1 : Above code will throw a warning if SwiftLint is not installed on the system. But if you want that all your team member will install it, you can make build failed using following script :

if which swiftlint >/dev/null; then
swiftlint
else
echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"
exit 1
fi

Note 2 : Now build your project (⌘B). SwiftLint will automatically identify warnings and errors in your code that does not comply with the default style guide line. Finally we have successfully integrated SwiftLint in our current project. But, If you will compile your project, you ended up with lots of warnings and errors. Even Xcode’s “Single View” project template doesn’t pass SwiftLint’s default validation.


B) Auto correct:


Some of the basic issues (such as whitespace at the end of a line) can be automatically fixed by SwiftLint. Just open the terminal and type the following command in your project root directory.

$ cd path/to/project/root/directory
$ swiftlint autocorrect
$ swiftlint autocorrect --path your_file.swift #For SwiftLint's auto correct on single file


C) To configure the behaviour of SwiftLint :


Now we have to fix all other issues that SwiftLint’s autocorrect was not able to do. But fixing all the issues one time it’s too much complex and time consuming. Fortunately, it provides configuration options to ‘enable/disable’ its pre defined rules. So, Initially I will disable all the rules and enable one by one to break down the bigger task into smaller chunks.


To get started, just create '.swiftlint.yml' in your project’s root directory and paste following contents in it.

disabled_rules:
- trailing_newline
- opening_brace
- empty_count
- comma
- colon
- force_cast
- type_name
- variable_name_min_length
- trailing_semicolon
- force_try
- function_body_length
- nesting
- variable_name
- conditional_binding_cascade
- variable_name_max_length
- operator_whitespace
- control_statement
- legacy_constant
- line_length
- return_arrow_whitespace
- trailing_whitespace
- closing_brace
- statement_position
- type_body_length
- todo
- legacy_constructor
- valid_docs
- missing_docs
- file_length
- leading_whitespace

- Some rules have parameters that you can configure, for example the Type Body Length, how many lines of code the body of a type is allowed to be, can be configured like this:

type_body_length:
- 300 # warning
- 400 # error

D) Summary points :

- To list all available SwiftLint’s rules type following command : ‘$ swiftlint rules’

a) All available rules which you can use are here.

b) You can download the example configuration file from here.

c) Followings are the valid rule identifiers, you can use any of them :
(empty_count , redundant_optional_initialization , trailing_semicolon , statement_position , type_name , unused_enumerated , todo , legacy_constant , force_cast , unused_closure_parameter , nimble_operator , number_separator , comma , sorted_imports , implicit_getter , legacy_cggeometry_functions , force_unwrapping , leading_whitespace , cyclomatic_complexity , control_statement , function_body_length , empty_parentheses_with_trailing_closure , dynamic_inline , type_body_length , unused_optional_binding , operator_whitespace , closure_spacing , prohibited_super_call , object_literal , valid_docs , vertical_whitespace , redundant_void_return , large_tuple , trailing_whitespace , mark , empty_parameters , legacy_nsgeometry_functions , shorthand_operator , closing_brace , class_delegate_protocol , colon , closure_parameter_position , nesting , switch_case_on_newline , file_header , conditional_returns_on_newline , trailing_newline , missing_docs , variable_name , redundant_nil_coalescing , private_unit_test , compiler_protocol_init , return_arrow_whitespace , operator_usage_whitespace , attributes , overridden_super_call , vertical_parameter_alignment , first_where , private_outlet , generic_type_name , explicit_init , legacy_constructor , closure_end_indentation , custom_rules , function_parameter_count , syntactic_sugar , trailing_comma , void_return , valid_ibinspectable , opening_brace , line_length , weak_delegate , force_try , redundant_string_enum_value , file_length)


Regards,
Nilesh

Thursday, January 19, 2017

Core data implementation in Swift 3.0 for iOS 8.0 and later versions.

Hi Everyone,

After a long long time, I'm back along with some creative things not just in Objective C but from now onwards, I'll start to post the articles and queries for Swift language too. Here, I would like to share core data implementation for Swift Language by just creating a singleton.

I've shared some examples for "Add, Update, Delete, Count" operations from my own experience and this will definitely help you to create your own. Just check the below contents :


 - ================================================================

class DBManager: NSObject
{
    //-- singleton declaration
    static let sharedDBManager = DBManager()
    
    override init() {
    }
    
    //MARK: - ================================
    //MARK: Core Data Delegate Methods
    //MARK: ================================
    
    //-- Application Document directory ...
    public lazy var applicationDocumentsDirectory: URL = {
        // The directory the application uses to store the Core Data store file. This code uses a directory named in the application's documents Application Support directory.
        let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return urls[urls.count - 1]
    }()
    
    //-- ManagedObjectModel ...
    private lazy var managedObjectModel: NSManagedObjectModel = {
        // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
        let modelURL = Bundle.main.url(forResource: "mydatabase", withExtension: "momd")!
        return NSManagedObjectModel(contentsOf: modelURL)!
    }()
    
    //-- Persistent Store Coordinator ...
    private lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
        // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
        // Create the coordinator and store
        let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
        let url = self.applicationDocumentsDirectory.appendingPathComponent("mydatabase.sqlite")
        var failureReason = "There was an error creating or loading the application's saved data."
        do {
            // Configure automatic migration.
            let options = [ NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true ]
            try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: options)
        } catch {
            // Report any error we got.
            var dict = [String: AnyObject]()
            dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
            dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
            
            dict[NSUnderlyingErrorKey] = error as NSError
            let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
            // Replace this with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
            abort()
        }
        
        return coordinator
    }()
    
    //-- ManagedObjectContext Creation
    lazy var managedObjectContext: NSManagedObjectContext = {
        var managedObjectContext: NSManagedObjectContext?
        if #available(iOS 10.0, *){
            managedObjectContext = self.persistentContainer.viewContext
        }
        else{
            // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
            let coordinator = self.persistentStoreCoordinator
            managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
            managedObjectContext?.persistentStoreCoordinator = coordinator
        }
        return managedObjectContext!
    }()
    
    //-- iOS - 10 : NSPersistentContainer
    @available(iOS 10.0, *)
    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
         */
        let container = NSPersistentContainer(name: "mydatabase")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                
                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        print("\(self.applicationDocumentsDirectory)")
        return container
    }()
    
    //-- Core Data Saving support
    func saveContext () {
        if self.managedObjectContext.hasChanges {
            do {
                try self.managedObjectContext.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
                abort()
            }
        }
    }
    
    //MARK: - ================================
    //MARK: Below is the example to get user based on cust_id
    //MARK: ================================
    
   
    func getUserWith(_ cust_id : String, completionHandler : @escaping(_ result : User?, _ error : NSError?) -> Swift.Void)
    {
        let context = self.managedObjectContext
        let request: NSFetchRequest<User>
        if #available(iOS 10.0, *) {
            request = User.fetchRequest()
        } else {
            request = NSFetchRequest(entityName: "User")
        }
        request.predicate = NSPredicate(format: "cust_id = %@", cust_id)
        do {
           let arrUser = try context.fetch(request)
            if arrUser.count > 0 {
                completionHandler(arrUser[0], nil)
            }
            else {
                completionHandler(nil, nil)
            }
        } catch let error as NSError {
            print("Could not save. \(error), \(error.userInfo)")
            completionHandler(nil, error)
        }
    }
      
    //MARK: - ================================
    //MARK: Below is the function to delete the records from the core-data table which are not available in Array fetched from backend server.
    //MARK: ================================
        
    func deleteVehicleInfoUsing(_ arrVehicle : Array<Any>)
    {
        print("Vehicle : \(arrVehicle)")
        let context = self.managedObjectContext
        let request: NSFetchRequest<Vehicle>
        if #available(iOS 10.0, *) {
            request = Vehicle.fetchRequest()
        } else {
            request = NSFetchRequest(entityName: "Vehicle")
        }
        request.predicate = NSPredicate(format: "NOT(vehicle_id IN %@)", arrVehicle)
        do {
            let arrVeh = try context.fetch(request)
            for obj_veh in arrVeh {
                context.delete(obj_veh)
            }
            do {
                try context.save()
            } catch let error as NSError {
                print("Could not delete vehicle. \(error), \(error.userInfo)")
            }
        } catch let error as NSError {
            print("Could not delete vehicle. \(error), \(error.userInfo)")
        }
    }
    
    //MARK: - ================================
    //MARK: To “Add” reservation record into the core data table. Likewise you can add your own record to the table.
    //MARK: ================================
    
    func saveReservation(_ obj_addreservation : AddReservation, completionHandler : @escaping(_ result : Bool,_ obj_reservation : Reservation?, _ error : NSError?) -> Swift.Void)
    {
        let context = self.managedObjectContext
        let entity = NSEntityDescription.entity(forEntityName: "Reservation", in: context)
        let obj_reservation = (NSManagedObject(entity: entity!,  insertInto: context) as! Reservation)
        
        obj_reservation.phoneID = obj_addreservation.phoneID
        obj_reservation.locationID = (obj_addreservation.locationID != nil) ? Int64(obj_addreservation.locationID!):0
        obj_reservation.licensePlate = obj_addreservation.licensePlate
        obj_reservation.provinceID = (obj_addreservation.provinceID != nil) ? Int64(obj_addreservation.provinceID!):0
        obj_reservation.vehicleMakeID = (obj_addreservation.vehicleMakeID != nil) ? Int64(obj_addreservation.vehicleMakeID!):0
        obj_reservation.vehicleTypeID = (obj_addreservation.vehicleTypeID != nil) ? Int64(obj_addreservation.vehicleTypeID!):0
        obj_reservation.vehicleColourID = (obj_addreservation.vehicleColourID != nil) ? Int64(obj_addreservation.vehicleColourID!):0
        obj_reservation.openDate = obj_addreservation.openDate
        obj_reservation.closeDate = obj_addreservation.closeDate
        obj_reservation.airlineCode = obj_addreservation.airlineCode
        obj_reservation.flightNum = (obj_addreservation.flightNum != nil) ? Int64(obj_addreservation.flightNum!):0
        obj_reservation.associationNumber = obj_addreservation.associationNumber
        obj_reservation.rewardRedemptionCoupon = obj_addreservation.rewardRedemptionCoupon
        obj_reservation.aeroplanNumber = obj_addreservation.aeroplanNumber
        obj_reservation.ticket_id = obj_addreservation.ticket_id
        
        do {
            try context.save()
            completionHandler(true,obj_reservation,nil)
        } catch let error as NSError {
            print("Could not save reservation. \(error), \(error.userInfo)")
            completionHandler(true, nil, error)
        }
    }
    
    //MARK: - ================================
    //MARK: To fetch all the records from the table in core data instead of specific one
    //MARK: ================================

    func fetchAllReservations(completionHandler : @escaping(_ result : [Reservation]?, _ error : String?) -> Swift.Void)
    {
        let context = self.managedObjectContext
        let request: NSFetchRequest<Reservation>
        if #available(iOS 10.0, *) {
            request = Reservation.fetchRequest()
        } else {
            request = NSFetchRequest(entityName: "Reservation")
        }
        do {
            let arrReservation = try context.fetch(request)
            if arrReservation.count > 0 {
                completionHandler(arrReservation, nil)
            }
            else {
                completionHandler([], "No reservation found.")
            }
        } catch let error as NSError {
            print("Could not fetch reservation. \(error), \(error.userInfo)")
            completionHandler([], error.localizedDescription)
        }
    }
    
    //MARK: - ================================
    //MARK: To fetch the count of records from the table in core data
    //MARK: ================================

    func getTotalReservation() -> Int
    {
        let context = self.managedObjectContext
        let request: NSFetchRequest<Reservation>
        if #available(iOS 10.0, *) {
            request = Reservation.fetchRequest()
        } else {
            request = NSFetchRequest(entityName: "Reservation")
        }
        request.includesPropertyValues = false
        
        do {
            let count = try context.count(for: request)
            return count
        } catch let error as NSError {
            print("Error: \(error.localizedDescription)")
            return 0
        }
    }
}

- ================================================================

Regards,
Nileshkumar M. Prajapati