Posts

Showing posts from May, 2018

Set the play and pause image for a button iOS swift

Solution: You had an option that you can set the image for a button in normal and selection mode. let playImage = UIImage(named: "ic_play_circle_outline_36pt");  let pauseImage = UIImage(named: "ic_pause_circle_outline_36pt");        audioPlayBtn.setImage( playImage , for: .normal)   audioPlayBtn.setImage( pauseImage , for: .selected)

open google maps and show direction from one place to another iOS swift.

Solution: I had a button in my app.I want to open google maps and navigation to that location from my current location when the user clicks.             if ( UIApplication . shared . canOpenURL ( URL (string: "comgooglemaps://" )!)){                 UIApplication . shared . o penURL ( NSURL (string:                     "comgooglemaps://?saddr=&daddr= \ ( lat ), \ ( long )&directionsmode=driving" )! as URL )             } else {                 NSLog ( "Can't open com.google.maps://" );             }

Add Button items to the Navigation Bar iOS swift. || Bar button item iOS swift

Solution: In navigationBar you can add buttons at right side and also in left side. The below are the code for adding the bar button items.     var addBtn: UIBarButtonItem ! In didload add the below code          addBtn = UIBarButtonItem (image:ic_mode_edit_white, style: . plain , target: self , action: #selector ( ViewController .didTapOnSave( _ :)))          self . navigationItem . rightBarButtonItems = [ addBtn ] Run the app and enjoy with cheers...

Convert CIImage to UIImage iOS swift.

Solution: Here the below function was used to convert the CIImage to UIImage in XCode.     // MARK: - convert image     func convert(cimage: CIImage ) -> UIImage     {         let context: CIContext = CIContext . init (options: nil )         let cgImage: CGImage = context. createCGImage (cmage, from: cmage. extent )!         let image: UIImage = UIImage . init (cgImage: cgImage)         return image      }

Add placeholder to textView iOS swift || Placeholder for UITextView iOS swift

Solution: In textfield we had an option for placeholder but it is not available for textView in XCode.No worries don't bang your heads on wall to handle this. I had the solution go ahead and enjoy. First you have to create a label and add it to textview if textView is empty then show the label.     var placeholderLabel : UILabel ! In viewdidload add the below code          self . addPlaceHolderToTextView ()             placeholderLabel . isHidden = ! textTV . text . isEmpty Also add the below function in your class.     // MARK: - PlaceHolders     func addPlaceHolderToTextView(){         placeholderLabel = UILabel ()         placeholderLabel . text = "Enter text"         placeholderLabel . font = UIFont . systemFont (ofSize: ( textTV . font ?. pointSize )!)          placeholderLabel . sizeToFit ()         textTV . addSubview ( placeholderLabel )         placeholderLabel . frame . origin = CGPoint (x: 5 , y: ( text

Bold the text that was serched by the user in iOS swift || change particular string color in the textfield in iOS swift

Solution: The below function will return the attributed string that was searched by the user with background color change. Also you can change the color of the text.      func boldSearchResult(searchString: String, resultString: String) -> NSMutableAttributedString {                 let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: resultString)         let pattern = searchString.lowercased()         let range: NSRange = NSMakeRange(0, resultString.characters.count)                 let regex = try! NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options())                 regex.enumerateMatches(in: resultString.lowercased(), options: NSRegularExpression.MatchingOptions(), range: range) { (textCheckingResult, matchingFlags, stop) -> Void in             let subRange = textCheckingResult?.range             attributedString.addAttribute(NSBackgroundColorAttributeName,value: UIColor.yellow, range: subRange!)         }         r

Based on My array size i want to hide and show my TableView iOS swift

Solution: Here we had the single line of code that will show and hide your tableview based on the size of array.         Tbl.isHidden = myList.count>0 ? false : true

alertViewcontroller example iOS swift

Solution: AlertViewcontroller is used for show alertView to the user to get simple inputs like okay and cancel.             let alertController = UIAlertController(title: "AVCam", message: message, preferredStyle: .alert)             alertController.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Alert OK button"), style: .cancel, handler: nil))             alertController.addAction(UIAlertAction(title: NSLocalizedString("Settings", comment: "Alert button to open Settings"), style: .default, handler: { action in                               }             })) let cancelActionButton = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in                 }                 alertController .addAction(cancelActionButton)             self.present(alertController, animated: true, completion: nil)

Create an imageview that will be in the bottom of the view for all devices like iPhone,Ipad... in iOS swift

Solution: Its very easy to create an imageview at the bottom of the screen in iOS. UIImageView(frame: CGRect(x: 0, y: self.view.bounds.size.height-40 ), width: self.view.bounds.size .width, height: 40))

Create a floating button that will came into entire app iOS swift

Solution: Create a floating button that will show in entire app and having to add an action at the particular viewcontroller.In appdelegate add the code in the declaration part.     var floatingBtn: UIButton! Add the functions in the appdelegate.      func createInfoButton() {         floatingBtn = UIButton(type: .custom) floatingBtn.backgroundColor = .black // color put your neadable color         floatingBtn.layer.cornerRadius = 20         floatingBtn.layer.borderWidth = 3         floatingBtn.backgroundColor = UIColor.white         floatingBtn.layer.borderColor = color.cgColor         floatingBtn.addTarget(self, action: #selector(showView(sender:)), for: .touchUpInside)     }             //    MARK: - Add Floating Button     func floatingButton(yPos:CGFloat,controller:UIViewController,tag:Int,isHidden:Bool) {         floatingBtn.frame = CGRect(x: controller.view.frame.size.width-55, y: yPos, width: 40, height: 40)         floatingBtn.tag = tag         floatingBtn.isHidden

Change the StatusBar textColor in swift and Objective c iOS

Solution: Swift: override var preferredStatusBarStyle : UIStatusBarStyle { return . lightContent } The above code will be used to display the lightcontent in the statusBar. Objective C: - (UIStatusBarStyle)preferredStatusBarStyle {     return UIStatusBarStyleLightContent; } Before implement that above method do the below steps In info.plist file set the variable UIViewControllerBasedStatusBarAppearance value to YES. In View Didload add the below code [self setNeedsStatusBarAppearanceUpdate];

Compress an image with fixed width iOS swift

Solution: The below code will return the Data with compressed image.You can give the image and the width of the  image. func compressImage(img:UIImage,givenWidth:CGFloat) ->Data {         print("before compression",UIImagePNGRepresentation(img)?.count)         print("before width and height",img.size)         let newWidth:CGFloat = givenWidth         let scale = newWidth / img.size.width         let newHeight = img.size.height * scale         UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))         img.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))         let newImage = UIGraphicsGetImageFromCurrentImageContext()         UIGraphicsEndImageContext()         var compression = 0.9         let maxCompression = 0.1                 print("after compression",UIImagePNGRepresentation(newImage!)?.count)         print("after width and height",newImage?.size)         var imageData = UIImageJPEGRepresentatio

add hours to particular date iOS swift

Solution: func addHours(hoursToAdd: Int) -> NSDate {         let secondsInHours: TimeInterval = Double(hoursToAdd) * 60 * 60         let dateWithHoursAdded: NSDate = self.addingTimeInterval(secondsInHours)                 //Return Result         return dateWithHoursAdded     }

Get the day of the week from date iOS swift

Problem: I want to get the day(0,1,2,3...) of the week from the particular date. Solution:     func getDayOfWeek(_ today:Date) -> Int? {         //        let formatter  = DateFormatter()         let myCalendar = Calendar(identifier: .gregorian)         let weekDay = myCalendar.component(.weekday, from: today)         return weekDay     } 0 means sunday,1 means monday etc

Get an upcoming date between two date iOS swift

Problem: I had two date with me fromdate and todate.I want to get the upcoming date(greater than today date). Solution:         func getUpcomingDate(fromDate: NSDate, toDate: NSDate)-> String{         var fromDatet = fromDate                 repeat {                                    if fromDatet.isGreaterThanDate(dateToCompare: NSDate()){                            return dateStr             }             fromDatet = fromDatet.addDays(daysToAdd: 1)         } while (fromDatet.isLessThanDate(dateToCompare: toDate) || fromDatet.isEqual(to: toDate as Date))                 return ""     } //adding the days to the date func addDays(daysToAdd: Int) -> NSDate {         let secondsInDays: TimeInterval = Double(daysToAdd) * 60 * 60 * 24         let dateWithDaysAdded: NSDate = self.addingTimeInterval(secondsInDays)                 //Return Result         return dateWithDaysAdded     } //check if less than date func isLessThanDate(dateToCompare: NSDate) -> Bo

Check particular region has my lattitude and longitude iOS swift

Problem: I had my latitude and longitude and i want to check it was nearby to the other coordinate(lattitude and longitude). Solution: let region = CLCircularRegion(center:  CLLocationCoordinate2D(latitude: (atitude), longitude: (longitide)), radius: CLLocationDistance(radius), identifier: "")                 if region.contains(CLLocationCoordinate2DMake(lat, long)) == true{ //if it contains that region for example if you give the radius as 100 then the other lat and long had inside that region it willl returns true }

How to check if the Dictionary contains a key iOS swift?

Problem: You had dictionary and it contains some set of keys.But you want to check the key exists before get the value. Solution: The function will return if key already there then true otherwise returns false     func getIfKeyExists(dict:NSDictionary,key:String) ->Bool {         if dict[key] == nil {             return false         } else {             return true         }     }  

How to create a segmented control and add the action to that and handle iOS swift?

Solution: First drag and drop the segmented control to your storyboard. Then add the action to the segmented control with value changed option. Then add the code inside the action. How many number of segments you had based on that you can add the cases in that. Code:          switch segmentControl.selectedSegmentIndex {         case 0:        break         case 1:        break        default:             break  }

How to check if the device is iPhoneX or not in iOS swift

Problem: I want to detect the phone is iPhone X or other models.Because based on that i want to change my app constraints. Solution: The below condition will be works if the device is iphone X.In else we can put the other phone model codes will execute. if UIDevice().userInterfaceIdiom == .phone && UIScreen.main.nativeBounds.height == 2436{ } else { //other device codes will be here }

Today extension show more and show less option to expand the tableView iOS swift

Problem: In iOS today extension it will show in notification area with show less and show more option.Based on that i want to display minimum one cell on if it will be in show more condition and display full data if it will be in show less mode. Solution: Below function we can change the height based on the user action      func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) { if (activeDisplayMode == NCWidgetDisplayMode.compact) {             self.preferredContentSize = maxSize         }         else {             //expanded             self.preferredContentSize = CGSize(width: maxSize.width, height: CGFloat(CGFloat(list.count*65  // you can replace the 65 with your cell height size                 )))         } }

Open main App via TodayExtension iOS Swift

Problem: I had developed an app with today extension.How do navigate to my main app when the user clicks any data in my extension? Solution: In Today extension if you click the logo default it will navigate to the app.You can use the below coding in your extension In extension write the below code:         let url = URL(string:"Widget://data you want to send to main app")         self.extensionContext?.open(url!, completionHandler: { (success) in             if (!success) {                 print("error: failed to open app from Today Extension")}         }) In your main app handle the data from the url and process it. In Main app write the below code:     func application(_ application: UIApplication, handleOpen url: URL) -> Bool     {         if url.scheme == "Widget" {             if let value = url.host             { "process the value here" }   }         return true   }

Today Extension Not working iOS swift || when click the today extension app opens and crashes it doesn't show errors iOS swift || widget crashed iOS

Problem: Today extension with grouping has working properly.But if i click the extension it was opened the app and within two seconds app crashes but nothing to get the crashlog it pointed in didfinishlaunching.Head broken.I had putted breakpoint on didfinsihlaunching options also not working. Solution: The app crashed bacause of i used this method is wrong. func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool { }  Use this method will work perfectly     func application(_ application: UIApplication, handleOpen url: URL) -> Bool }

JSON content Type in iOS

Solution: Json is a way of data parsing method that used in web application to mobile application.You can sed the data from server in the format of object. The data contents will be like Nsdictionay,Nsarray,Nsstring and so on.. The content type is application/json. The default encoding format for data is UTF-8.

Coredova pass the data to javascipt function from pushNotification iOS Objective C

Problem: How to solve the push notification data to evaluate from javascript in objective c Cordova project? Solution: In Cordova you get the data from push notification in the form of dictionary and you can parse it and evaluate in objective c.But if you want to pass it to the javascript function in Cordova and evaluate then the below function was useful. -( void )webCall:( NSString *)notifyJS {     if ([ self . webView respondsToSelector : @selector (stringByEvaluatingJavaScriptFromString:)]) {         dispatch_sync ( dispatch_get_main_queue (), ^{                          [( UIWebView *) self . webView stringByEvaluatingJavaScriptFromString :notifyJS];         });              } else {         [ self . webViewEngine evaluateJavaScript :notifyJS completionHandler : nil ];     }      } In Webstring you can call the javascript function with its parameters.The above function i used it as notifyJS

Tab bar hidden not working iOS swift

Problem: I had tried to hide my tab bar in my viewwillappear function but it was not woking.But the line of code is executed. Solution: I understand that it was caused because of UI execution.So try to execute the code after delay of 1 second.It will works well.

Export my notes from notes app from one Mac to another

Solution: Goto your notes app and select the note that you want to share.Then goto file->Export as pdf and then download the file share it to another mac and then copy the notes from the PDF and paste it to your notes app.Enjoy to share 😍

Wireless debugging in iOS || Xcode New features

Solution : We had the new feature with Xcode 9 for debugging without cable.Cable crack issues soled. In first time we need to connect the phone with cable.After that we don't need the cable.. Steps: Connect the cable to the phone and goto window -> devices and simulators in xcode In devices it will show your phone.Select that and check the option connect via network. After that disconnect the cable and the device will be shown in your Xcode via network. Wowww enjoy without cabling...but one more your device will not be chargable...