Posts

Showing posts from October, 2018

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                 }             }         } ...

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     ...

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)          ...

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      ...

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.

Create Line with arrow in iOS Objective C

Solution: In iOS you can create a Line using CGContextref.The below code is used for draw a line in a view in x1,y1, is 0,0 and x2,y2 is 20,20. Also add the cap in the end of the line to show the line as arrow      CGContextRef  ctx =  UIGraphicsGetCurrentContext ();      CGRect  rect =  CGRectMake ( 0 ,  0,20,20 )      CGContextClearRect (ctx, rect);     CGContextSetStrokeColorWithColor(ctx, color.CGColor);     CGContextSetLineCap(ctx, kCGLineCapRound);     CGContextSetLineWidth(ctx, 10);     CGContextSetAlpha(ctx, 1);     CGContextMoveToPoint(ctx, 0, 0); //add the cap              CGPoint fPoint=CGPointMake(0,0);         CGPoint ePoint=CGPointMake(20,20);         CGFloat capHeight = 1 * 4.0f;         CGFloat angle = [self angleWithF...

Create Line in iOS Objective C

Solution: In iOS you can create a Line using CGContextref.The below code is used for draw a line in a view in x1,y1, is 0,0 and x2,y2 is 20,20.     CGContextRef  ctx =  UIGraphicsGetCurrentContext ();    CGRect  rect =  CGRectMake ( 0 ,  0,20,20 );    CGContextClearRect (ctx, rect);   CGContextSetStrokeColorWithColor(ctx, color.CGColor);    CGContextSetLineCap(ctx, kCGLineCapRound);    CGContextSetLineWidth(ctx, 10);    CGContextSetAlpha(ctx, 1);    CGContextMoveToPoint(ctx, 0, 0);    CGContextAddLineToPoint(ctx, 20, 20);    CGContextStrokePath(ctx);     CGContextDrawPath (ctx,  kCGPathFillStroke );

Create circle in iOS Objective C with and without fill

Solution: In iOS you can create a circle using CGContextref. The below code is used for draw a circle in a view with 0 x axis,0 y axis,width 20 and height 20..      CGContextRef  ctx =  UIGraphicsGetCurrentContext ();      CGRect  rect =  CGRectMake ( 0 ,  0,20,20 )      CGContextClearRect (ctx, rect);      CGContextSetLineWidth (ctx, 10 );      CGContextStrokeEllipseInRect(UIGraphicsGetCurrentContext(), rect); If you want to fill the rectangle then add the below code          CGContextSetFillColorWithColor(ctx, color.CGColor);         CGContextFillEllipseInRect(UIGraphicsGetCurrentContext(), rect);

Create rectangle in iOS Objective C with and without fill

Solution: In iOS you can create a rectangle using CGContextref.The below code is used for draw a rectangle in a view with 0 x axis,0 y axis,width 20 and height 20..     CGContextRef ctx = UIGraphicsGetCurrentContext ();     CGRect  rect = CGRectMake ( 0 , 0,20,20 )     CGContextClearRect (ctx, rect);     CGContextSetLineWidth (ctx, self . layerWidth );      CGPathRef path = CGPathCreateWithRect ( self . bounds , NULL );     CGContextAddPath (ctx, path);     CGContextDrawPath (ctx, kCGPathFillStroke ); If you want to fill the rectangle then add the below code          CGContextSetStrokeColorWithColor (ctx, color. CGColor );

Create UITableViewCell in two types iOS swift

Solution: 1) In iOS you can create tableViewCell inside your tableView and assign a class. Then in cellforRow you can use the cell using reusableIdentifier. 2) You can also create a cell in xib and insert a cell inside that and assign a class to that cell.Then in your ViewController Viewdidload method register that cell using the xib and cell identifier.Like below         self . tableView . register ( UINib (nibName: "Xibname" , bundle: nil ), forCellReuseIdentifier: "tableCell" ) After that same as reuse the cell in the cellforRow delegate method.

Set the Gradient color in iOS swift

Solution: The below code is used to set the gradient color to the particular view first declare the colors     let topColorsList: [ String ] = [ "#f12711" ]      let bottomColorsList: [ String ] = [ "#f5af19" ]         let gradientLayer: CAGradientLayer = CAGradientLayer()         gradientLayer.frame.size = cell.moreView.frame.size                  gradientLayer.colors = [hexStringToUIColor(hex: topColorsList[indexPath.row]).cgColor,hexStringToUIColor(hex: bottomColorsList[indexPath.row]).cgColor]         //Use diffrent colors         cell.moreView.layer.addSublayer(gradientLayer) The above code needs the below function for get the color from hexstring   func hexStringToUIColor (hex: String ) -> UIColor {         var cString: String = hex. trimmingCh...

How to check the string is Nil or Not and

Solution: The function will return empty string if your variable contains nil value otherwise it will returns its value. func noNilString(string: AnyObject?) -> String { if let category = string as? String { return category } else { return "" } }

get the current city from coordinates iOS swift

Solution: In iOS you can get the current city from your coordinates using the below function. Code:     func getCurrentCity(loc: CLLocation , completion: @escaping ( _ result: String ) -> Void ,                         failure: ( _ err: NSError ) -> Void ) {         // Get user's current location name         let geocoder = CLGeocoder ()         var placeMark: String = ""         geocoder. reverseGeocodeLocation (loc) { (placemarksArray, error) in                             if (placemarksArray?. count )! > 0 {                     // City                                      ...

Download image from web and set it to the ImageView iOS swift

Solution: In iOS you can download the image from asynchronously and set it to the imageView.It will not disturb your main thread and UI updates. You can use the below function as a common and every time you can call the function with its url and imageView. Code:     func downloadImage(url: URL ,imageView: UIImageView )   {         print ( "Download Started" )         getDataFromUrl (url: url) { (data, response, error)   in             guard let data = data, error == nil else { return }             print (response?. suggestedFilename ?? url. lastPathComponent )             print ( "Download Finished" )             DispatchQueue . main . async () { () -> Void in                 imageView. image = UIImage (data: data)     ...

add tab or spaces and newline in html string iOS Swift

Solution: If you are using \r then it will remove the unwanted spaces in your string. If you want to add spaces in your string better go ahead with spaces you can add manually in the string. If you want to add new line then add \n inside your string. 

Remove the unwanted charaters in a phone Number iOS swift

Solution: You can get the phone number from the user in textfield and format it as a valid phone number using the below expression.   let ValidNo = number. value . stringValue . replacingOccurrences (of: "[^0-9+]" , with: "" , options: NSString . CompareOptions . regularExpression , range: nil ) The above expression will truncate the special characters in the phone Number.So you can save the phone number directly to your database.

Convert the Dictionary to JSON iOS swift

Solution: The below function was used to convert the dictionary to jsonobject. You can call the function like below. convertToJSON (dict: dictionary) Code: func convertToJSON(dict: NSDictionary ) -> String {         if let theJSONData = try ? JSONSerialization . data (             withJSONObject: dict,             options: []) {             let theJSONText = String (data: theJSONData,                                      encoding: . ascii )             print ( "JSON string = \ ( theJSONText! )" )             return theJSONText!         }         return ""     }

Model with inner array predicate in iOS swift || Dictionary with inner array predicate

Solution:    In iOS models cannot be able to predicate with inner array.So you can convert the model into dictionary and predicate with multilevel inner arrays. In model you cannot be able to access the model properties directly from predicate. You can use ANY with inner array predicates like below CODE:      let  Predicate = NSPredicate(format: "ANY lists.Lists.name contains[cd] %@" , searchText) it has lists -> Lists -> name

How to create a compound predicate in iOS? || multiple predicates in swift

Solution: You can merge one or more predicates to form a predicate.Because if you do in a single predicate you can have more confusions with and or.         let innerPredicate = NSPredicate(format: "ANY name contains[cd] %@" , searchText)         let innerQuantPredicate = NSPredicate(format: "ANY quantity contains[cd] %@" , searchText)         let outerQuantPredicate = NSPredicate(format: "ANY slNo contains[cd] %@" , searchText)                  let compundPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: [outerPredicate, innerPredicate, titlePredicate])