Wednesday, 8 May 2019

Example links



1) Collapsed and Expanded table view for both swift and objective c

http://www.anexinet.com/blog/expandable-collapsible-uitableview-sections/

http://www.iostute.com/2015/04/expandable-and-collapsable-tableview.html

2) Upload image to server

https://doszhan.com/2017/04/23/objective-c-get-image-from-gallery-camera-and-send-via-http/


Image upload example with swift and php

http://swiftdeveloperblog.com/image-upload-example/

https://stackoverflow.com/questions/28570574/nsurlsessionuploadtask-dont-upload-image-with-parameters


http://ioscake.com/send-post-request-using-nsurlsession.html

Upload image through AFNetworking

https://stackoverflow.com/questions/35947930/uploading-an-image-using-afnetworking-3-0

http://codeobjectivec.blogspot.in/2016/04/upload-image-file-to-server-in-ios.html



3) Difference launch screens for iPad and iPhone

https://stackoverflow.com/questions/38077313/load-different-launch-screen-for-ipad-iphone




4) UITextField delegates

https://code.tutsplus.com/tutorials/ios-sdk-uitextfield-uitextfielddelegate--mobile-10943



5) Google places AutoComplete

https://github.com/spoletto/SPGooglePlacesAutocomplete

https://devhub.io/repos/chenyuan-SPGooglePlacesAutocomplete

http://sweettutos.com/2015/09/30/how-to-use-the-google-places-autocomplete-api-with-google-maps-sdk-on-ios/


https://www.youtube.com/watch?v=gRQUoHleCGM

https://www.youtube.com/watch?v=5jIoGV6DC9w

https://developers.google.com/places/ios-api/autocomplete


6) Google MapKit

https://www.youtube.com/watch?v=GYzNsVFyDrU


Google maps marker example and maps types


https://developers.google.com/maps/documentation/ios-sdk/


Swift example

https://theappspace.com/google-maps-sdk-ios-using-swift-4/

Objective cExample

https://lunapps.com/blog/ios-google-maps-integration/



7) AFNetWorking

https://code.tutsplus.com/tutorials/networking-made-easy-with-afnetworking--mobile-10741



8) Icons online site

https://icons8.com/icon/set/minus/all



9) Send notifications with firebase to PHP

https://stackoverflow.com/questions/39426330/ios-sending-notification-with-firebase

https://www.cumulations.com/blogs/87/how-to-send-push-notifications-in-php-to-ios-devices-using-fcm





10) Push notification custom sound

https://stackoverflow.com/questions/40485717/ios-unable-to-play-custom-sound-for-remote-notifications


https://stackoverflow.com/questions/20367038/update-badge-count-for-push-notifications-in-ios7

https://stackoverflow.com/questions/11153631/increment-the-push-notification-badge-iphone

http://api.shephertz.com/tutorial/Push-Notification-iOS/


11) Core data

Fetch every N th record

https://stackoverflow.com/questions/8651104/how-to-fetch-every-nth-object-using-core-data


12) UITableView header selectable

https://stackoverflow.com/questions/19996566/how-to-make-uitableview-header-selectable


13) Pausing, Resuming and Cancelling Downloads


https://www.raywenderlich.com/567-urlsession-tutorial-getting-started














Read JOSN Array Objects



let jsonArray = [
                    "array": [12.34, 56.78],
                    "users": [
                        [
                            "id": 987654,
                            "info": [
                                "name": "jack",
                                "email": "jack@gmail.com"
                            ],
                            "feeds": [98, 23443, 213239, 23232]
                        ],
                        [
                            "id": 654321,
                            "info": [
                                "name": "jeffgukang",
                                "email": "jeffgukang@gmail.com"
                            ],
                            "feeds": [12345, 56789, 12423, 12412]
                        ]
                    ]
                ]
               
                print("Result = \(String(describing: jsonArray))")
                print("JSON Count: \(jsonArray.count)")
                print("JSON Arr one : \(jsonArray["array"]!)")
                print("JSON Arr one count : \(String(describing: jsonArray["array"]?.count))")
                print("JSON arr 1st Obj = \(String(describing: jsonArray["array"]![0]))")
                print("JSON arr 2nd Obj = \(String(describing: jsonArray["array"]![1]))")
//                print("arr One = \(String(describing: jsonArray["array"]![2]))")//Fatal error: Index out of range
               
                let array = NSMutableArray()
                for index in 0..<jsonArray.count {
                    array.addObjects(from: [jsonArray["array"]![index]])
                }
                print("JSON arr one array: \(array)")
               
               
                print("JSON arr two : \(jsonArray["users"]!)")
                print("JSON arr two count : \(String(describing: jsonArray["users"]?.count))")
                                        // OR
                print("JSON arr two count : \(jsonArray["users"]?.count as Optional)")
                print("Json arr two 1st obj : \(jsonArray["users"]![0])")
                print("Json arr two 2nd obj : \(jsonArray["users"]![1])")

                let val1 = (jsonArray["users"]![0] as! [String: Any])["id"]
                let val2 = (jsonArray["users"]![0] as! [String: Any])["info"]
                let val3 = (jsonArray["users"]![0] as! [String: Any])["feeds"]
               
                print(val1 as Any)
                print(val2 as Any)
                print(val3 as Any)
               
               
                var infoArr2: [Any] = []
                var idArr2: [Any] = []
                var feeds2: [Any] = []
                for i in 0..<(jsonArray["users"]!).count {
                    infoArr2.append((jsonArray["users"]![i] as! [String: Any])["info"]!)
                    idArr2.append((jsonArray["users"]![i] as! [String: Any])["id"]!)
                    feeds2.append((jsonArray["users"]![i] as! [String: Any])["feeds"]!)
                }
                print("********************************************************")
                print(infoArr2)
                print(idArr2)
                print(feeds2)
                print("********************************************************")
               
                var email: [Any] = []
                var name: [Any] = []
                for i in 0..<infoArr2.count {
                    email.append(((jsonArray["users"]![i] as! [String: Any])["info"]! as! [String: Any])["email"] as! String)
                    name.append(((jsonArray["users"]![i] as! [String: Any])["info"]! as! [String: Any])["name"] as! String)
                }
                print(email)
                print("Email1 : \(email[0])")
                print(name)
                print("name1 : \(name[0])")

Set background image for UIAlertController







UIAlertController * alert=   [UIAlertController
                                  alertControllerWithTitle:@"Title" //alert Title
                                  message:@"Msg sfdgfdjsgajgasgasgsfjkgsfjkgfsgksdgfhvbhbdfjkvbsbvjsdfbvjsdbvbdsvbdjbvdbvdbjvdbjvbdsfbvj v hsfv hfs vhjsf vf hv sjfvbjs f" //Your Message
                                  preferredStyle:UIAlertControllerStyleAlert];
   
    UIView *firstSubview = alert.view.subviews.firstObject;
    UIView *alertContentView = firstSubview.subviews.firstObject;
    for (UIView *subSubView in alertContentView.subviews) {
        subSubView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"OTP.png"]];
    }

    UIAlertAction* ok = [UIAlertAction
                         actionWithTitle:@"OK"
                         style:UIAlertActionStyleDefault
                         handler:^(UIAlertAction * action)
                         {
                             [alert dismissViewControllerAnimated:YES completion:nil];
                           
                         }];
   
   
    [alert addAction:ok];
   
    [self presentViewController:alert animated:YES completion:nil];

Core data






import UIKit
import CoreData

struct DBRecord {
    var user:String
    var pass:String
    var age:String
}

class ViewController: UIViewController {

    @IBOutlet weak var userName: UITextField!
    @IBOutlet weak var password: UITextField!
    @IBOutlet weak var age: UITextField!
    @IBOutlet weak var textView: UITextView!
    
    var appDelegate:AppDelegate!
    var context: NSManagedObjectContext!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        //1)
        appDelegate = UIApplication.shared.delegate as? AppDelegate
        //2)
        context = appDelegate.persistentContainer.viewContext
        
//        struct Person {
//            var name: String
//            var surname: String
//            var phone: Int
//            var isCustomer: Bool
//        }
//
//        var contacts: [Person] = []
//
//        let person1: Person = Person(name: "Jack", surname: "Johnson", phone: 2, isCustomer: false)
//        let person2: Person = Person(name: "alex", surname: "a", phone: 3, isCustomer: false)
//
//        contacts.append(person1)
//        contacts.append(person2)
//
//        for contact in contacts {
//            print("\(contact.name)")
//        }
        
    }

    @IBAction func save(_ sender: Any) {
        
        //Steps
        //        Add Records to Core Data
        //        The process of adding the records to Core Data has following tasks
        //
        //        1)Refer to  persistentContainer
        //        2)Create the context
        //        3)Create an entity
        //        4)Create new record
        //        5)Save values for the records for each key
        
//        //2)
//        let context = appDelegate.persistentContainer.viewContext
        //3)
        let entity = NSEntityDescription.entity(forEntityName: "Users", in: context)
        let newUser = NSManagedObject(entity: entity!, insertInto: context)
        //4)
        newUser.setValue(userName.text, forKey: "username")
        newUser.setValue(password.text, forKey: "password")
        newUser.setValue(age.text, forKey: "age")
        //5)Save
        do {
            try context.save()
        } catch {
            print("Failed saving")
        }
        
    }
    
    @IBAction func fetch(_ sender: Any) {
        
        //Steps
        //        Fetch from Core Data
        //        The process of fetching the saved data from is very easy as well. It has the following task
        //
        //        1)Prepare the request of type NSFetchRequest for the entity
        //        2)Fetch the result from context in the form of array of [NSManagedObject] (Here we can fetch result in type of dictionary, NSManagedObjectID and NSNumber also) //See this "leanne" answer https://stackoverflow.com/questions/40191598/swift-3-nsfetchrequest-distinct-results
        //        3)Iterate through an array to get value for the specific key
        
        // Create Fetch Request
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
//        request.predicate = NSPredicate(format: "age = %@", "12")
//        request.predicate = NSPredicate(format: "age <= %@", "12")
//        request.predicate = NSPredicate(format: "age > %@", "12")
//        request.predicate = NSPredicate(format: "age < %@ && age > %@", "13", "10")
//        request.predicate = NSPredicate(format: "age < %@ || age > %@", "12", "11")
//        request.predicate = NSPredicate(format: "%K CONTAINS %@", "username", "u")
//        request.predicate = NSPredicate(format: "%K CONTAINS[c] %@", "username", "U")
//        request.predicate = NSPredicate(format: "%K CONTAINS[c] %@ AND %K < %i", "username", "U", "age", 12)
//        request.predicate = NSPredicate(format: "%K BEGINSWITH[cd] %@", "username", "u")
//        request.predicate = NSPredicate(format: "username CONTAINS[cd] %@ AND age < %d", "u", 12)

        
        
        /*
         //Add NSCompoundPredicate
         let predicate1 = NSPredicate(format: "age = 12")
         //        let predicate2 = NSPredicate(format: "%K = %@", "username", "user1")
         let predicate2 = NSPredicate(format: "%K = %@ || %K = %@", "username", "user1", "username", "user2")
         //        request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate1, predicate2])
         //        request.predicate = NSCompoundPredicate(notPredicateWithSubpredicate: predicate1)
         request.predicate = NSCompoundPredicate(orPredicateWithSubpredicates: [predicate1, predicate2])
         */
        
        
        
        // Add Sort Descriptor
//        let sortDescriptor = NSSortDescriptor(key: "username", ascending: true)
//        let sortDescriptor = NSSortDescriptor(key: "age", ascending: true)
//        request.sortDescriptors = [sortDescriptor]

        /*
        // Create Predicate
        request.predicate = NSPredicate(format: "%K == %@", "username", "user")
        
        // Add Sort Descriptor
        let sortDescriptor1 = NSSortDescriptor(key: "username", ascending: true)
        let sortDescriptor2 = NSSortDescriptor(key: "age", ascending: true)
        request.sortDescriptors = [sortDescriptor1, sortDescriptor2]
        */
        
        /*
        let nameSortDescriptor = NSSortDescriptor(key: "username", ascending: true)
        let priceSortDescriptor = NSSortDescriptor(key: "password", ascending: true)
        request.sortDescriptors = [nameSortDescriptor, priceSortDescriptor]
        */
        
        
        
//        request.fetchOffset = 5//It will stop first 5 records
//        request.fetchLimit = 2//It will fetch only 2 records
//        request.fetchBatchSize = 20
//
//        To get specific column
//        //Link 1): https://stackoverflow.com/questions/46317889/could-not-cast-value-of-type-nsknownkeysdictionary1-to
//        //Link 2): https://stackoverflow.com/questions/40191598/swift-3-nsfetchrequest-distinct-results
//        request.resultType = .dictionaryResultType
//        request.propertiesToFetch = ["username"]//It's get only one cloumn
//        request.propertiesToFetch = ["username", "password"]//It's get two columns
//        request.returnsDistinctResults = true//To get distinct elements
//
//        request.returnsObjectsAsFaultrs = false
        
        do {
            let result = try context.fetch(request)
//            print(result)
            //Procedure 1
            //Create arrays to store values
            var userArr = [String]()
            var passArr = [String]()
            var ageArr = [String]()
            //Procedure 2
            //Create custom type array to store values
            var DBArray:[DBRecord] = []//Custom type array (Struct)
            for data in result as! [NSManagedObject] {
                //Procedure 2
                let u = data.value(forKey: "username") as! String
                let p = data.value(forKey: "password") as! String
                let a = data.value(forKey: "age") as! String
                DBArray.append(DBRecord(user: u, pass: p, age: a))
                //Procedure 1
                userArr.append(data.value(forKey: "username") as! String)
                passArr.append(data.value(forKey: "password") as! String)
                ageArr.append(data.value(forKey: "age") as! String)
            }
            if DBArray.count > 0 {
                textView.text = "\(DBArray)"
            }
            for dbrecord in DBArray {
                print(dbrecord)
            }
        } catch {
            print("Fetch Failed")
        }
        
    }
    
    @IBAction func deleteRecord(_ sender: Any) {
        
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
        //request.predicate = NSPredicate(format: "age = %@", "12")
//        request.returnsObjectsAsFaults = false
        
        do {
            let result = try context.fetch(request)
             for data in result as! [NSManagedObject] {
                context.delete(data)
                do {
                    try context.save()
                } catch {
                    print("Failed saving")
                }
            }
        } catch {
            print("Delete Failed")
        }
    }
    
    @IBAction func update(_ sender: UIButton) {
        
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
        request.predicate = NSPredicate(format: "age = %@", "age1")
        
        do {
            let result = try context.fetch(request) as? [NSManagedObject]
            if result?.count != 0 { // Atleast one was returned
                // In my case, I only updated the first item in results
                result![0].setValue("19", forKey: "age")
                do {
                    try context.save()
                } catch {
                    print("Failed saving:\(error)")
                }
            } else {
                print("No recors found...")
            }
        } catch {
            print("Update Failed : \(error)")
        }
    }
    
    

}

Friday, 3 May 2019

Shared class iOS


import UIKit

class SharedClass: NSObject {

    static let sharedInstance = SharedClass()
    
    var transparentView:UIView?
    var spinner = UIActivityIndicatorView()
    
    
//    var url =  "Your url here
    
    let ver = "1.0"
    let noNetMsg = "No internet connection. Please connect."
    
//    //Show activity indicator
//    func activityIndicator(view:UIView) {
//
//        DispatchQueue.main.async {
////            if let window = UIApplication.shared.keyWindow {//Conditionally unwrap it instead of force unwrap
//
//                //let window = UIApplication.shared.keyWindow! //Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
//            self.transparentView = UIView()
//            self.transparentView?.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height)
//            self.transparentView?.backgroundColor = UIColor.black.withAlphaComponent(0.4)
//            view.addSubview(self.transparentView!)
//
//                if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad {
////                    self.spinner = UIActivityIndicatorView(style: .whiteLarge)
//                    self.spinner = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
//                    self.spinner.frame = CGRect(x: 0, y: 0, width: 60, height: 60)
//                } else {
////                    self.spinner = UIActivityIndicatorView(style: .white)
//                    self.spinner = UIActivityIndicatorView(activityIndicatorStyle: .white)
//                    self.spinner.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
//                }
//                self.spinner.center = view.center
//            self.transparentView?.addSubview(self.spinner)
//                self.spinner.startAnimating()
//
//                DispatchQueue.main.asyncAfter(deadline: .now() + 30.0) {//Stop spinner after 10 Sec's
//                    self.stopActivityIndicator()
//                }
//            }
////        }
//    }
    
    //Show activity indicator
    func activityIndicator(view:UIView) {
        
        DispatchQueue.main.async {
            if let window = UIApplication.shared.keyWindow {//Conditionally unwrap it instead of force unwrap
            
//                let window = UIApplication.shared.keyWindow! //Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
                self.transparentView = UIView()
                self.transparentView?.frame = CGRect(x: 0, y: 0, width: window.frame.width, height: window.frame.height)
                self.transparentView?.backgroundColor = UIColor.black.withAlphaComponent(0.4)
                window.addSubview(self.transparentView!)
                
                if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad {
                    //                    self.spinner = UIActivityIndicatorView(style: .whiteLarge)
                    self.spinner = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
                    self.spinner.frame = CGRect(x: 0, y: 0, width: 60, height: 60)
                } else {
                    //                    self.spinner = UIActivityIndicatorView(style: .white)
                    self.spinner = UIActivityIndicatorView(activityIndicatorStyle: .white)
                    self.spinner.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
                }
                self.spinner.center = view.center
                self.transparentView?.addSubview(self.spinner)
                self.spinner.startAnimating()
                
                DispatchQueue.main.asyncAfter(deadline: .now() + 30.0) {//Stop spinner after 10 Sec's
                    self.stopActivityIndicator()
                }
            }
        }
    }
    
    
    //Stop activity indicator
    func stopActivityIndicator() {
        DispatchQueue.main.async {
            self.spinner.stopAnimating()
            self.spinner.removeFromSuperview()
            self.transparentView?.removeFromSuperview()//Some times getting error here
        }
    }
    
    /*
    //Present alert on top of all windows
    func alertWindow(title: String, message: String) {
        //Calling
        //SharedClass.sharedInstance.alertWindow(title:"", message:"")
        DispatchQueue.main.async(execute: {
            let window = UIWindow(frame: UIScreen.main.bounds)
            window.rootViewController = UIViewController()
//            window.windowLevel = UIWindow.Level.alert + 1
            window.windowLevel = UIWindowLevelAlert+1
            
            let alert2 = UIAlertController(title: title, message: message, preferredStyle: .alert)
            let defaultAction2 = UIAlertAction(title: "OK", style: .default, handler: { action in
            })
            alert2.addAction(defaultAction2)
            
            window.makeKeyAndVisible()
            
            window.rootViewController?.present(alert2, animated: true, completion: nil)
        })
    }
    */
    
    //Email validation
    func isValidEmail(email: String) -> Bool {
        let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
        var valid = NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: email)
        if valid {
            valid = !email.contains("Invalid email id")
        }
        return valid
    }
   
    
    private override init() {
        
    }
    
}

//Alert function
extension UIViewController {
    func showAlert(title: String, msg: String) {
        DispatchQueue.main.async {
            let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }
    }
}

//Set TF shadow in login VC
extension UITextField {
    func TFProperties() {
        layer.shadowColor = UIColor(red: 199/255, green: 217/255, blue: 223/255, alpha: 1.0).cgColor
        layer.shadowOpacity = 1
        layer.shadowOffset = CGSize.zero
        layer.shadowRadius = 5
        layer.borderColor = UIColor(red: 199/255, green: 217/255, blue: 223/255, alpha: 1.0).cgColor
        layer.borderWidth = 1
        layer.cornerRadius = 4
    }
}


Difference between == and ===

Difference between == and === https://stackoverflow.com/questions/24002819/difference-between-and == operator checks if their ...