Posts

Showing posts from 2018

iOS constraint guidelines

Solution: Constraint are very easy if you understand that with logically.First you have to think your need for design then proceed that. It had an alignments that with left,right,top,bottom also width,height and center of the view. If your view wants to be aligned left then first set the left,top and bottom.If the width varies based on the view then don't set the width.Also height too... If your two views or buttons wants to be the same width.then select both the views and select that option called equal width. If you wants that view wants to be aligned vertically or horizontally to the superview then select the view and check the options.

iOS tab bar did select in second time image goes to smaller in tab Bar controller

Solution: If you are setted the insets in storyBoard you want to set in both sides.Like if you set the inset in bottom 2 then set the top to -2 (or) if you set the left to 2 then set right to -2. It will solve your problem.Also check that if you set the image in didselect then it might be the problem.So check carefully to set the different image when select the tab bar. Also check the constraints.

Create IPA in Xcode

Solution: Apple had a magic technics for distribution.They had the tool named testFlight with internal and external testers to review the app and testing purpose. If you want to distribute an app with other then you have to export the IPA file with it's provisioning profiles and upload it to Diawi or some other sites then send the link to the customer or tester. And one more if you had a enterprise account it's very easy you can export the app and upload it to your website and send the link to the tester.

Change the dictionary Value in an array iOS swift

Solution: In NSDictionary you cannot be able to change the value.If you can convert the NSDictionary to NSMutableDictionary then you can change the value in it.              var dic =  dataArray . object (at: 0 ) as ! NSDictionary             let mute = NSMutableDictionary ()             mute. addEntries (from: dic as ! [ AnyHashable : Any ])                  mute. setValue ( "value" , forKey: "keyValue" )             self . dataArray . replaceObject (at: 0, with: NSDictionary (dictionary: mute))

Set the slider value based on the AVAudiosession volume || mobile system volume based slider change in iOS swift

Solution: If you are adjusting the volume in your phone volume button based on slider change you can follow the below steps     override func viewDidDisappear( _ animated: Bool ) {         AVAudioSession.sharedInstance().removeObserver( self , forKeyPath: "outputVolume" )         do { try AVAudioSession.sharedInstance().setActive( false ) }         catch { debugPrint( " \ ( error )" ) }     }          func listenVolumeButton() {         let audioSession = AVAudioSession.sharedInstance()         do {             try audioSession.setActive( true )         } catch {             print( "some error" )         }         audioSession.addObserver( self , forKeyPath: "outputVolume" , options: NSKeyValueObservingOptions.new, context: nil )     }          override func observeValue(forKeyPath keyPath: String ?, of object: Any ?, change: [ NSKeyValueChangeKey : Any ]?, context: UnsafeMutableRawPointer

How to disable the selection in TableView iOS swift?

Solution: If you want to disable the selection for entire tableView then use the below code for that. tableView.allowsSelection = NO; Or you can use the below code cell.selectionStyle = UITableViewCellSelectionStyle.None If you want to disable the selection for particular row you can do that in cell for row function disable the userinteraction for the cell. Cell. UserInteractionEnabled = false

How to embed custom font in iPhone application?

Solution: Xcode 10 or greater if you add the font files into the project and it will be added directly when you try to set font in storyboard it will be listed. But in previous time it was not possible.First you have to add the font file to your project. After that open the Info.plist file and set the key named  UIAppFonts change the datattype to array and set the each fontfilename into that you had added already. Save the Info.plist file [UIFont fontWithName:@"CustomFontName" size:12]   Then use the font as above.

Delete a record in iPhone addressBook iOS swift

Solution: You can have to store the contact identifier in your database.Using that contact identifier you can navigate the app to view the contactEdit page.It can have an option to delete the contact

Difference between Synchronous and Asynchronous in iOS swift?

Solution: Synchronous: Synchrounous waits until the process finished after that only the next process will continue executing. It will be waiting to the user to complete the previous task. Asynchronous: Asynchronous will be the simultaneous execution of process.Like another process will not wait for that process.It will be executing in the background.After the completion we can display the process result with its data. For example loading the image in the tableView will be executed using the asynchronous task because user don't want to wait for the result of image it will be loaded in the background. 

App crashes when i try to delete a row in TableView iOS swift

Solution: If you are tried to delete the row and not delete the element from array it will be occurres. So first you have to execute the delete row code then remove the indexpath.row element from array then reload the table.It will works

How to get the inBetween days from fromdate and Todate in iOS swift?

Solution: If you want to get the everyday from between tow days then follow the below code you can proceed with that. You can give the Extension as date and get the function using the below code. Code: Class Viewcontroller:UIViewController { } extension Date {     func inBetweenDates(fromDate: Date ,toDate: Date ) -> NSMutableArray {         let dateArray = NSMutableArray ()         var from = fromDate                  while from <= toDate {             var dates: Date = from             dates = truncateSecondsForDate (fromDate: dates)             dateArray. add (dates)             dates = from. addingTimeInterval ( 60 * 60 * 24 * 1 )             from = dates         }         return dateArray     } }

Remove Duplicate element in an NSMutableArray iOS swift

Solution: In NSMUtablearray we can have to save the array of data or add a data to that array.But it will accept the duplicate elements.It cannot have primary keys to restrict that.So you can follow the below code to remove the duplicate elements in the final moment. func removeDuplcate(arr: NSMutableArray )-> NSMutableArray {         let temp: NSMutableArray = NSMutableArray ()         for i in 0 ..<arr. count {             if !temp. contains (arr[i]) {                 temp. add (arr[i])             }         }         return temp     }

Get an image from it's name from Document directory iOS swift

Solution: If you saved an image to document directory in your app you cannot have to save the full url path to your database or coredata. Because every time document directory path will be modified.So you can save the image name in your database and fetch it later using the below code. func getImage(name: String )-> UIImage {         let fileManager = FileManager . default         let imagePAth = ( NSSearchPathForDirectoriesInDomains (. documentDirectory , . userDomainMask , true )[ 0 ] as NSString ). appendingPathComponent (name)         if fileManager. fileExists (atPath: imagePAth){             if UIImage (contentsOfFile: imagePAth) != nil {                 return UIImage (contentsOfFile: imagePAth)!             } else {                 return   imageLiteral(resourceName: "default image you saved")             }         }         else {             return   imageLiteral(resourceName: "default image you saved")  

Set the navigation bar color in UIIMagePicker for my app theme color iOS swift

Solution: You can use the below code to set the navigation bar colour for the imagepicker from your app app. extension UIImagePickerController {     open override func viewWillLayoutSubviews() {         super . viewWillLayoutSubviews ()                  self . navigationBar . topItem ?. rightBarButtonItem ?. tintColor = UIColor (). white//here you can put your app theme color         self . navigationBar . topItem ?. rightBarButtonItem ?. isEnabled = true              } }

UITabbar shows syrinc when i went to background and enter into foreground in my app iOS swift

Solution: In iOS 11 it has a bug so try the below code in appdelegate it will works good. class TabBar: UITabBar {     private var cachedSafeAreaInsets = UIEdgeInsets.zero          override var safeAreaInsets: UIEdgeInsets {         if #available ( iOS 11.0 , *) {             let insets = super .safeAreaInsets             if insets.bottom < bounds.height {                 cachedSafeAreaInsets = insets             }         } else {             // Fallback on earlier versions         }         return cachedSafeAreaInsets     } }

Is that possible to set a primary key in CoreData iOS swift?

Solution: There is no primary key available in coredata.It has more than a database.It will had relationShips and entities. If you want to implement primary key then you can do onething to store an identifier with Integer and use it as primary key.But you cannot be set as primary key in coredata. So you can do that fetch the data from coredata with predicate and check that identifier is available or not then save it in coredata.

Implement to get fetch the data from Contacts and implement the search in firstName,LastName and phone numbers

Solution: You cannot be able to search the firstName,LastName and phone number in contacts List because it is a dictionary with multitypes.So predicate will not be possible.So you can get the contact and save it in a dictionary with firstName and LastName as two keys and phone number as one key with concatenating the all phonenumbers in a single contact as a string and implement the search in the dictionary will works good.

What is strong and weak properties in iOS ?

Solution: Strong: Strong is used to describe a property that will never be return nil.It must had an amount of data.For example if you referred the Employer to employee you can do it as strong relationship. Weak: Weak is used to describe a property that if it returns nil or it will returns a data.It will never be a strong value.You can refer from employee to employer it will be less connected.

Coredata data storing types iOS swift

Solution: In most of the time we are storing the Coredata as in sql format.But it had different type to save the data. XML Binary Sqlite In-Memory NSpersistant store is commonly used for storing and retrieving the data in coredata.You can use sortdescriptors to fetch the organized data based on the attributes.

iOS 9 pdf file not able to show to the user

Solution: After iOS 10 only the apple provides the feature for file manager. So you have an access for listing the file that are stored in your device. But if you want to show the PDF file to the user then you can use webView inside your app and get the url and open it in the webView. But file listing is not possible before iOS 10.

Difference between cross platform and Native in iOS and android

Solution: Native: iOS : In native app development you can have their own tool to develop and distribute the app like in iOS Xcode is available.In android android Studio is available. In iOS we are using the design as with xml language with it UI tools like label and button.Development to control the design and action are made by two languages.One is objective C and Swift languages. It will provide the development and distribution based environment for the user. Android: In android we can using xml language for design purpose Java for development purpose.Now a days we are also using kotlin for development. Cross Platform: Cross platforms are used for single development and multiple type of deployment.So we can develop the apps and distribute to multiple environment like iOS,Android,Windows,Ubuntu,... In that cross platform you can design by using HTML and Javascript and develop by Javascript. Cordova is maximum used. Phonegap Titanium iOnic are the tools t

iOS swift variable value came as optional

Solution: In swift it has two type of objects one is unwrapped and another one is wrapped. Unwrapped: let name = nameValue as? Int Wrapped: let name = nameValue as! Int If you tried with unwrapped then it will came as optional value.So if you can use as wrapped format it will came with original value. One more thing that if you assigned other datatype value then unwrapped function will not force close your app.Because it will skip the data if not matches the data type. In wrapped format it will force closes your app when you assigned the other datatype values.

# Pragma mark in Swift || Annotations in swift

Solution: In swift you can use the annotations for code folding and formatting.You can easily access your need of line using pragma marks. //  MARK :- Title for identification // write your codes here It will format your code via the title you had given

How to get the selected row or selected cells in UITableView iOS swift

solution: You can get the selected rows or selected cells by using the below code.It will return the array of indexPath.You can get and set it by using the arrays. For selected Rows: let selected = tableView.indexPathsForSelectedRows For selected Sections: let selected = tableView.indexPathsForSelectedSections

Remove a particular notification from notification tray iOS swift

Solution: Yes it's definitely possible.If you have an option to save the notification identifier in your database or coredata then it's easy. You can find the notification from the scheduled notification of your app.             UNUserNotificationCenter .current().removeDeliveredNotifications(withIdentifiers: [ids])

How to save the image as string from my textView or TextField and display it in iOS swift

Solution: In iOS you can easily set the emoji stickers to the textField because they already accepting the emoji in textfileds. Follow the below steps to easily set the home emoji to your textfield. 1) First you have to convert that image to string.Its not a big problem.Just you have to set it between "".That's it. 2)If you had a textfield named nameTF then you just set the emoji as below nameTF.text = "🏠"

Font name is already set but not changed for the text iOS swift

Solution: If you set the font to your textfield with font name then must be double check it.If you set the wrong font then only it came as HelverticaNue as default font. Must set the correct name.

Set the Italic to the UITextView iOS swift

Solution:     @IBAction func didTapOnItalic( _ sender: Any ) {         let textV = self . TextView         if  textV != nil {                          var fonts = textV. font              fonts = (fonts?. isItalic )! ? fonts?. removeitalic () : fonts?. setItalic () textV. fontName =  fonts!. fontName          }     } extension UIFont {     var isItalic: Bool     {         return fontDescriptor . symbolicTraits . contains (. traitItalic )      }     func setItalic()-> UIFont     {         if isItalic {             return self                      } else {             var symTraits = fontDescriptor . symbolicTraits             symTraits. insert ([. traitItalic ])             let fontDescriptorVar = fontDescriptor . withSymbolicTraits (symTraits)             return UIFont (descriptor: fontDescriptorVar!, size: 0 )          }     } func remo

Set bold to one UITextView iOS swift

Solution: The below function is used for set the bold to the TextView.     @IBAction func didTapOnBold( _ sender: Any ) {         let  textView = TextView         if  textView != nil {             var fonts = textView. font             fonts = (fonts?. isBold )! ? fonts?. removeBold () : fonts?. setBold () textView.font =  fonts!. fontName         }     } extension UIFont { var isBold: Bool     {         return fontDescriptor . symbolicTraits . contains (. traitBold )      } //set the bold func setBold() -> UIFont     {         if isBold {             return self                      } else {             var symTraits = fontDescriptor . symbolicTraits             symTraits. insert ([. traitBold ])             let fontDescriptorVar = fontDescriptor . withSymbolicTraits (symTraits)             return UIFont (descriptor: fontDescriptorVar!, size: 0 )         }

Get the Indexpath from button action of one cell iOS swift

Solution: If you had already added an action to one button or switch then you can easily get the indexPath for that button using the below function.Code extension UITableView { func indexPathForView(view: AnyObject ) -> NSIndexPath ? {         let originInTableView = self . convert ( CGPoint . zero , from: (view as ! UIView ))         return self . indexPathForRow (at: originInTableView) as ! NSIndexPath     } } You can add the above extension for tableView and get the indexPath.You can call the function inside the button action like below.      @IBAction func didTapOnSwitch( _ sender: AnyObject ) {         let swit = sender as ! UISwitch         let index = self . myPlacesTbl . indexPathForView (view: swit) }

How to check is UITextView is underlined or not iOS swift

Solution: You cannot have any functions to check that.But you can test it by using the below method     func attributes(value: Int ) -> NSAttributedString {         let textV = self . TextView         let newTextView: UITextView ! = UITextView . init ()         var attrs = [ NSFontAttributeName :  self . TextView . font ,                      NSForegroundColorAttributeName :  self . TextView . textColor ,                      NSUnderlineStyleAttributeName : value] as ! [ String : Any ]         var attributedString = NSMutableAttributedString (string: "" )         let buttonTitleStr = NSMutableAttributedString (string:( self . TextView . text )!, attributes:attrs)         attributedString. append (buttonTitleStr)         newTextView. attributedText = attributedString         return newTextView. attributedText     } In your textview you can check it by using the below code             let attributedString = self

Swift playground how to stop the frame size becomes 1024*768

Solution:      When your viewController loads first ViewdidLoad() function will be called.That time your screen frame not yet to be updated. So you want to wait for the time that viewWillAppear() or ViewDidLayoutSubviews() functions called.That time you can check that size of your page. You don't want to wait for the function ViewdidAppear() will be called.

How to check iOS version in that device using Myapp iOS swift

Solution: Now a days apple had a method that will closure your viewcontroller or method that will execute based on the os version in the device.   @available ( iOS 10.0 , *) //you can code here @end or you can code like below              let dev = UIDevice.current.systemVersion.hashValue

iOS app is Ready for sale State in app store but not showing app in itunes store

Solution: If you uploaded the app and status is in ready for sale then it will take some time for showing the app in appstore.Because apple will update all the servers all over the world. It will take some time to show in itunes app store.So be patient to wait to show your app in the appstore. It will not be miss or duplicate.In previous times apple had taken more time for review and update.But now a days they had quick response with app store approval.So no issues.

How to add existing Frameworks in XCode iOS swift

Image
Solution: In your project Xcode select the project. Select your target.Then goto build phases tab   select link binary with libraries.Select the + button and add your framework to the project and use that.

Xcode product -> Archieve disabled when try to archieve

Solution: In your xcode near Run Button it had your target name and simulator selection option. If you want to archieve the project and upload it then you must have to select that "Generic ios device" option.Then only the archieve option will be enable. If you selected any simulator or your realtime device then archive option will be disabled. So must check that.

Codesign error: Provisioning profile cannot be found after deleting expired profile in my mac

Solution: If you deleted the profile in your mac then you will not be able to build your app in development and distribution. If you updated the certificate in development site then goto xcode -> Preference -> then select accounts In right side menu it had download manual certificates.Click that button and download the profiles. Goto xcode project and find the error and select the long string and find it in your project.Erase that line in your project and goto project and clean up the project. Goto target and select the newly downloaded profiles for your development and distribution and run.

how to enable button when all textfields filled in tableviewcell(SWIFT)

Solution: The below function is used to check the that all textfields are filled in a tableViewCell.You can pass the cell to the function it will return the boolean when one textfield is empty .Otherwise it will return true. func enableBtn(cell: UITableViewCell )-> Bool {         var isEnable: Bool = true         for textF in cell. subviews {             if textF. isKind (of: UITextField ) {                 let textFild = textF as ! UITextField                 if textFild. text == "" {                     isEnable = false                     return isEnable                 }             }         }         return isEnable     }

Fatal error: unexpectedly found nil while unwrapping an Optional value uitextfield

Solution: If it says optional value accessing then first you have to check that your outlet to the textField is connected or not in storyboard. If it was connected then check that select the textfield and check if one or more outlets are connected to the single textfield. One more if you copied the textfield from other project and unfortunately delete the outlet in the code then also the error came.So double check it with only the outlet issue.

Create a dropDown Menu with array of values iOS swift

Solution: It was easy to show a dropdown menu when click on one button. Goto podfile and add the below code in that     pod 'DropDown' Update the pod in command line.It will install the dropdown in your app Then goto your required Viewcontroller and import dropdown like below. import DropDown In you button action add the below code     func didTapOnBtn( _ sender: AnyObject ){         let btn = sender as ! UIButton          let dropDown = DropDown ()          dropDown. anchorView = sender as ? AnchorView          dropDown. direction = . any         dropDown. dataSource = [ "list1","list2","list3" ]         dropDown. cellNib = UINib (nibName: "Cell" , bundle: nil )         dropDown. width = 150         dropDown. customCellConfiguration = { (index: Index , item: String , cell: DropDownCell ) -> Void in             guard let

iOS Data types and Usage

AnyObject: If you had a dynamic data that was changable in future then you can declare an object as anyobject. var data:AnyObject! NSMutableArray:   If you want an array that will be modify on run time then use NSMutableArray.You can add or remove an object at runtime. You can also add array of values in that. NSArray: If you had an array that will not be change then you can use it as NSArray.Once you can assign values but not able to add.

Xcode error when try to archieve the app shows invalid authentication

Solution : If it shows that invalid authentication when try to archieve the app then the account password was changed in that apple ID. So follow the below steps and solve that. 1) Goto Xcode -> Preference and select Accounts 2) In left it had list of accounts.If your account is already there and password required to sign then enter the password. 3)Otherwise no accounts then click the plus icon then it shows menu -> select appleID and click continue -> enter your appleID and password and finish the setup 4)After that your account will be shown in left side menu. 5)Now you can try to archieve the app and upload it will works..Happy Coding.... 

Convert Dictionary to string in swift4 iOS

Solution:   do {                          let theJSONData = try JSONSerialization . data (                             withJSONObject: dic ,                             options: JSONSerialization . WritingOptions (rawValue: 0 ))                         let theJSONText = NSString (data: theJSONData,                                                    encoding: String . Encoding . ascii . rawValue )                        let str  = String (describing: theJSONText)                     } catch let error as NSError {                         // handle error                     }

Multiple commands produce '/Users/system/Library/Developer/Xcode/DerivedData/myapp-bqlhjkbcgsncmxenozofsiqccrps/Build/Intermediates.noindex/ArchiveIntermediates/myapp/InstallationBuildProductsLocation/Applications/myapp.app/Assets.car

Image
Solution: Goto xcode->File->workspace settings Change New build system to Legacy build system. After that clean the derived data and build it will works good

Search implementation with tableView iOS swift

Solution: First you have to create two arrays for the implementation. One array for initially fetch and save all the data. Second one for searched filtered data. When the user clicks the search button then clear the dataArray and filter from main array. The class will be like below. class  SearchViewController: UIViewController, UISearchBarDelegate {      @IBOutlet weak var searchBar: UISearchBar !      var myArray: NSMutableArray = NSMutableArray()      var myFilteredArray: NSMutableArray = NSMutableArray()      override func viewDidLoad() { //fetch the data save in  myArray }      override func viewWillAppear( _ animated: Bool ) {          searchBar.becomeFirstResponder() }     // MARK: - SearchBar delegate          func searchBarSearchButtonClicked( _ searchBar: UISearchBar ) {         self .FilterResults(searchText: searchBar.text!)      

Open an URL in safari iOS swift || validate URL and open iOS swift

Solution: It will validate the url if it was null then it will not open the url.Otherwise it will be opened. If let condition was used to avoid the crash if the url is not valid.             if let url = URL (string: urlString) {                         UIApplication . shared . open (url, options: [:], completionHandler: { (success) in                             print ( "Open url : \ ( success )" )                          }) }

Create a web link to be valid HTTP or HTTPS iOS swift

Solution: If you had a url with website name but it does not contain any HTTP or HTTPS.If you faced any problem when connect to that website because of that then follow the below code.   if urlString. hasPrefix ( "https://" ) || urlString. hasPrefix ( "http://" ){             } else {                 urlString = "http:// \ ( urlString )"             } The above code will append the string with prefix.So no issues will come.Enjoy coding.