Post

Replies

Boosts

Views

Activity

Expandable UIView inside Navigation Bar can't be clicked/tapped
Hello Team we facing a problem with a UIView inside of a Navigation Bar what we need to achieve is to place a UIView (SwiftUI Wrapper) on the middle of the Navigation bar Here's how it looks like right now that's already complete, but now the problem that we are facing is that the View is not detecting the clicks/taps on the 'dates and 'travelers' here's the Code for the View private lazy var sharedUIPlaybackView: UIView = { let containerView = UIView().withAutoLayout() containerView.backgroundColor = .red containerView.styleBorder(color: .systemPink, width: 1) let propertySearchCriteria = PropertySearchCriteriaBuilder(hotelSearchParameters: viewModel.hotelSearchParameters).criteria var swiftUIView: SwiftUIView<LodgingPlaybackWrapper>! = nil swiftUIView = SwiftUIView( LodgingPlaybackWrapper(propertySearchCriteria: propertySearchCriteria, playbackUpdateNotificationSender: nil, componentHandler: { [weak self] componentId in self?.componentReady(componentId) }), viewDidLayoutSubviewsCallback: { [weak self] in let newHeight = swiftUIView.frame.size.height if newHeight != self?.sharedUIPlaybackViewHeightConstraint?.constant { self?.sharedUIPlaybackViewHeightConstraint?.constant = newHeight self?.additionalSafeAreaInsets.top = 200 } } ).withAutoLayout().withAccessibilityIdentifier("searchPlayback") sharedUIPlaybackViewHeightConstraint = containerView.heightAnchor.constraint(equalToConstant: 0) sharedUIPlaybackViewHeightConstraint?.isActive = true swiftUIView.backgroundColor = .blue swiftUIView.styleBorder(color: .orange, width: 1) containerView.addSubview(swiftUIView) containerView.addConstraints([ swiftUIView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: Spacing.spacing4x), swiftUIView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -Spacing.spacing4x) ]) self.view.bringSubviewToFront(swiftUIView) swiftUIView.isUserInteractionEnabled = true swiftUIView.layer.zPosition = 1 return containerView }() my first suspicion was that the this part of the code was not expanding correctly viewDidLayoutSubviewsCallback: { [weak self] in let newHeight = swiftUIView.frame.size.height if newHeight != self?.sharedUIPlaybackViewHeightConstraint?.constant { self?.sharedUIPlaybackViewHeightConstraint?.constant = newHeight self?.additionalSafeAreaInsets.top = 200 } } but after I place border and background colors on the views was clear for me that it was expanding properly, so I added some modifiers for the view like swiftUIView.isUserInteractionEnabled = true swiftUIView.layer.zPosition = 1 but didn't work, I'm asking for a solution and different point of view for the code to be more cleaner and do the best implementation posible. This Navigation bar should be treated as a custom Navigation Bar, or it is good for us to expand and treat the Navigation bar like this? (expanding and adding a Custom View) thanks in advance to anyone who read this. here's the View Hierarchy
1
0
317
May ’24
Generates all possible subsets of a given set, excluding the empty set. (non sorted)
I notice that this operation is expensive for the code (2^set.size). I'm looking the best practices and implementations more likely a re-work this code goes to a infinite bucle and freezes the app until it's done func generateSubsets(set: Set<String>) -> Set<Set<String>> { if set.count == 1 { return [set] } let first = set.map { item -> Set<String> in var clone = set clone.remove(item) return clone } let second = first.map(generateSubsets) var subSets = second.reduce(Set<Set<String>>()) { accumulator, elements in var clone = accumulator for element in elements { clone.insert(element) } return clone } subSets.insert(set) return subSets } Example For input ["qual1", "qual2", 'qual3"] the combinations can be: ["qual1#qual2#qual3", "qual1#qual2", "qual1#qual3", "qual2#qual3", "qual1", "qual2", "qual3"]
4
0
455
Mar ’24
edit certain section in viewForFooterInSection
Hey guys I'm having some struggles when trying to understand how to edit certain section for a viewForFooterInSection note the edit occurs when the user types something and this function gets call, that is already managed override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return prepareFooterView(tableView: tableView, section: section) } the question is how can I access certain section for me to edit the title on it? the function for footherview is: func prepareFooterView(tableView: UITableView, section: Int) -> UIView?{ guard let tableView = tableView as? LightTableView else { return UIView() } guard section <= TableSection.all.count else { return UIView() } ///the section is obtained here let section = TableSection.all[section] var title = "" switch section { case .detailsFooterView: title = "card_details_section_footer".localized case .nickname: if nickname?.isValidNickName == false { return prepareSpecificMessageInFooterView(with: "card_nickname_section_footer_error".localized, errorMessage: true) } title = "card_nickname_section_footer".localized case .fastlink: title = "earn_rewards_section_footer".localized default: title = "" } var footerView = tableView.standardFooterView(withTitle: title, textAlignment: .left, accessibilityIdentifier: section == .nickname || section == .fastlink || section == .detailsFooterView ? "NicknameFooterViewID" : nil, labelPadding: UIEdgeInsets(top: 12, left: 16, bottom: 0, right: -16)) return section == .nickname || section == .fastlink || section == .detailsFooterView ? footerView : nil } I would like to edit the case .fastlink: when a flag is turned ON the section here: num TableSection: Int { case details case detailsFooterView case nickname case fastlink case scan static var all: [TableSection] = isUs ? [.details, .detailsFooterView, .nickname, .fastlink] : [.details, .detailsFooterView, .nickname, .fastlink, .scan] } I guess this is not clear for me because this is running live instead of reloading the entire screen for example indexPath.row == 1
1
0
372
Jun ’22
Incremental compilation has been disabled: it is not compatible with whole module optimization on Release build configuration
Hey Developers I'm facing some strange situation, I'm getting multiples issues related to optimization on Release build configuration, I'm using Xcode 13.2.1 project is separated in 4 markets and multiples frameworks none of the markets have dependencies from each other, issue only appears when the market RefrreshAtPumpAUS Release is build, on the other side for Debug everything is functional and the app build fine. here's my Podfile: Podfile in order to add the : def adobe_manager_pods into the framework: CoolMasterUtilsFramework as the project is in 4 different markets had to added in the different markets like this:    target 'RefrreshAtPumpNL' do           # Pods for RefrreshAtPump     common_pods     adobe_manager_pods --> here       target 'RefrreshAtPumpUS' do        # Pods for RefrreshAtPump    common_pods    firebase_pods    adobe_campaign_pods    adobe_manager_pods. --> here       target 'RefrreshAtPumpUK' do             # Pods for RefrreshAtPump    common_pods    adobe_manager_pods --> here but for the AUS market(RefrreshAtPumpAUS) is quite different already had added similar PODS   target 'RefrreshAtPumpAUS' do        # Pods for RefrreshAtPump    common_pods    firebase_pods    adobe_experience_pods. ->> here they have this so, I added the 2 remaining that I needed for that specific market.   def adobe_experience_pods    pod 'AEPAudience', '~> 3.0’ ------->> THIS ONE    pod 'ACPUserProfile', '~> 2.2’ ------->> THIS ONE    pod 'AEPEdgeIdentity', '~> 1.0'    pod 'AEPEdgeConsent', '~> 1.0'    pod 'AEPCore', '~> 3.0'    pod 'AEPIdentity', '~> 3.0'    pod 'AEPSignal', '~>3.0'    pod 'AEPLifecycle', '~>3.0'    pod 'AEPUserProfile', '~> 3.0'    pod 'AEPEdge', '~> 1.0'    pod 'AEPMessaging', '~> 1.0'    pod 'AEPAssurance', '~> 3.0', :configurations => ['Debug']   end so if I run the project in all other markets as RELEASE or DEBUG everything goes well, but only for RELEASE on RefrreshAtPumpAUS shows errors like this:  multiple errors I've tried adding lines inside the RefrreshAtPumpAUS like this: 1.- post_install do |installer| 2.- Pod update 3.- delete all Derived data 4.- in Build settings -> Apple Clang - Code generation -> Optimization level to None[-O0] 5.- in Build settings -> Build active architecture only -> ALL to YES 6.- in podfile -> delete this line use_frameworks! and adding use_modular_headers!  7.- in Build settings -> Swift compiler -> Code generation -> Incremental to all Error 1
18
0
12k
Mar ’22
Set an array of arrays inside of UICollectionView that's inside a UITableView and return the correct number of items?
I am trying to get a UITableView with a UICollectionView to show the following data set correctly inside the UICollectionViews. the array which contains all this information is arregloDeArreglos here's the data - some : 1 [![dads][1]][1] However, when I scroll horizontally inside the UICollectionViews, the data will get all messed up. [1]: https:// i.stack. imgur. com/z9bw7 . png [2]: https://i. stack. imgur.com/lCS13 . png as you can see in both pictures here's my code table delegate and data source } uicollection delegate and datasource } uiCollectionviewCell }
13
0
1.6k
Mar ’21
UIcollectionView with array no loading sections
Hi, im struggle with my cell model it's only showing my array position 0 what i'm trying to reach is show in each UICollectionView the information inside arregloBidimencional which contains let episodes: [episodess]? and let tack: Int? episodess is my main struct for the didSet inside each UICollectionviewCell and tack is my identifier for each array of [episodess] } var arraySeasonsEpisodes: [episodess] = [] its type of episodess so my model to get the previous data is } so the didset in UICollectionViewCell it's set like this } this is how i storage the data from the json dictionary }
16
0
2.1k
Mar ’21
UICollectionView Inside of UItableViewCell no horizontal scrolling
Hi, i'm having this issue using Xcode 12.2 were i can't scroll in horizontal direction a UICollectionView, i have try multiples answers from the forum and none of then work for me first of all what i'm only trying to achieve is the scroll horizontally. Heres my UITableView declaration on the View: }() here's the Delegate and DataSource protocols in VC: } This is the code for UICollectionView declaration on the NumberOfSeasonsCell or UITableViewCell }() Protocols for the UICollectionView } i've read that i should store the last position of the Table for scrolling the UICollectionView but i've tried but not work for me here's the UICollectionViewCell }
4
0
4.7k
Mar ’21
Expandable Cell numberOfRowsInSection with Section
Hi developers im having this trouble with expandable cells sections when using return arrayUiText[section].nombre.count on numberOfRowsInSection, only returns 1 cell and that's correct because it only have 1 number in the array, but my question is how could i return more than one because i have 3 different cells but returning is been a struggle for me as you can see my arrayUiText as multiples names in diffent arrays, i could archieve my goal just adding multiples names on 1 array, but i could only use 1 SectionHeader and that's not what i wanted to do nombre: ["dasdad dasda", "asdasdasda", "asdasdsa"] like this. i try to numberOfRowsInSection return 3 but it collapses     typeOfPasajeroNameLastName(isExpanded: false, pasajeroNumber: ["Pasajero 1"], pasajeroType: ["Adulto"], nombre: ["dasdad dasda"], apellido: ["asdasd asdas"], birthDate: ["24/05/1994"]),     typeOfPasajeroNameLastName(isExpanded: false, pasajeroNumber: ["Pasajero 2"], pasajeroType: ["Adulto"], nombre: ["asdad"], apellido: ["asda asdasd"], birthDate: ["21/04/1994"]),     typeOfPasajeroNameLastName(isExpanded: false, pasajeroNumber: ["Pasajero 3"], pasajeroType: ["Bebé"], nombre: ["asdas"], apellido: ["asdasd asdass"], birthDate: ["08/08/2018"])   ]   extension PasajerosPaso2View: UITableViewDelegate, UITableViewDataSource {       func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {          if !arrayUiText[section].isExpanded{         return 0       }     return arrayUiText[section].nombre.count //this returns 1 i want returning 3         }       func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {               if indexPath.row == 0 {       let cell = tableView.dequeueReusableCell(withIdentifier: "pasajerosData", for: indexPath) as! PasajerosPaso2Cell       cell.selectionStyle = .none       cell.tipoDeDatoTextField.text = arrayUiText[indexPath.section].nombre[indexPath.row]       cell.tipoDeDatoTextField.delegate = self       print("indexpath 0: \(arrayUiText[indexPath.section].nombre)")       return cell     }     if indexPath.row == 1{       let cell = tableView.dequeueReusableCell(withIdentifier: "pasajerosApellidos", for: indexPath) as! PasajerosApellidosCell       cell.selectionStyle = .none       cell.tipoDeDatoTextField.text = arrayUiText[indexPath.section].apellido[indexPath.row]       cell.tipoDeDatoTextField.delegate = self       print("indexpath 1: \(arrayUiText[indexPath.section].apellido)")       return cell     }           else {       let cell2 = tableView.dequeueReusableCell(withIdentifier: "pasajerosBirthday", for: indexPath) as! PasajerosDateCell       cell2.selectionStyle = .none       cell2.tipoDeDatoTextField.text = arrayUiText[indexPath.section].birthDate[indexPath.row]       print("indexpath 2: \(arrayUiText[indexPath.section].birthDate[indexPath.row])")       return cell2     }                     }       func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {           return 60   }       func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {     print(indexPath.row)               }   func numberOfSections(in tableView: UITableView) -> Int {     return 3   }           func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {     let headerView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: tableView.frame.width, height: 50))     let headerCell = tableView.dequeueReusableCell(withIdentifier: "titleCelll") as! TitleCell     headerView.addSubview(headerCell)     headerView.backgroundColor = .white     headerCell.pasajeroNumber.text = arrayUiText[section].pasajeroNumber.first     headerCell.pasajeroType.text = arrayUiText[section].pasajeroType.first     let tapGesture5: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleExpandClose2))     tapGesture5.numberOfTapsRequired = 1     tapGesture5.numberOfTouchesRequired = 1     headerCell.isUserInteractionEnabled = true     headerCell.addGestureRecognizer(tapGesture5)     headerCell.tag = section     print(headerCell.tag)     return headerView         }           func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {       return 50     }                 }   @objc func handleExpandClose2(sender: UITapGestureRecognizer) {     print("Trying to expand and close section...")     //delegate?.cerrarLista1(self)     let section = sender.view?.tag ?? 0     // we'll try to close the section first by deleting the rows     var indexPaths = [IndexPath]()     for row in arrayUiText[section].nombre.indices {       let indexPath = IndexPath(row: row, section: section)       indexPaths.append(indexPath)     }     let isExpanded = arrayUiText[section].isExpanded     arrayUiText[section].isExpanded = !isExpanded     if isExpanded {       pasajerosTableView.deleteRows(at: indexPaths, with: .fade)     } else {       pasajerosTableView.insertRows(at: indexPaths, with: .fade)     }   }
0
0
419
Dec ’20
basic auth URLSession POST
Hi developers im trying to do a request like my postman using basic auth with an Username &amp; password, but i can't archieve, heres what i have done so farthis is how postman look likeAuthorization-&gt; Type -&gt;Basic Auth username: example_Username password: example_PasswordBody-&gt; form-dataKEY: grant_type VALUE: passwordKEY: username VALUE: test@gmail.comKEY: password VALUE: 03ac674216f3e15c761ee1a5e255f067953623c8b388b4459e13f978d7c846f4first i tryied this wayfunc postDataFormRequest(resource: TokenRequest, completion: @escaping (Result&lt;Token, NetworkError&gt;) -&gt; Void) { let headers = [ "Username": "example_api", "Password": "example_api_password", "Content-Type": "application/form-data" ] //this information comes from TokenRequestStruct once i call it form my VC let body = "grant_type=\(resource.grant_type)&amp;username=\(resource.username)&amp;password=\(resource.password)" guard let url = URL(string: "example/") else { return } var request = URLRequest(url: url) request.httpMethod = HTTPMethods.POST request.timeoutInterval = 60 request.httpBody = body.data(using: .utf8) request.allHTTPHeaderFields = headers URLSession.shared.dataTask(with: request) { (data, response, error) in guard let data = data, error == nil else { completion(.failure(.domainError)) return } let result = try? JSONDecoder().decode(Token.self, from: data) if let result = result { DispatchQueue.main.async { completion(.success(result)) } } else { DispatchQueue.main.async { completion(.failure(.decodingError)) } } }.resume() }using this method response =CredStore - performQuery - Error copying matching creds. Error=-25300, query={ atyp = http; class = inet; "m_Limit" = "m_LimitAll"; ptcl = http; "r_Attributes" = 1; sdmn = "oauth2/client"; srvr = "3.216.253.237"; sync = syna;}tried to fix it by using arbitrary loads = YESdidn't workSecond waystatic func getPostString(params:[String:Any]) -&gt; String { var data = [String]() for(key, value) in params { data.append(key + "=\(value)") } return data.map { String($0) }.joined(separator: "&amp;") } static func formData(url:URL, params:[String:Any], finish: @escaping ((message:String, data:Data?)) -&gt; Void) { var request = URLRequest(url: url) request.httpMethod = "POST" let postString = self.getPostString(params: params) request.httpBody = postString.data(using: .utf8) var result:(message:String, data:Data?) = (message: "Fail", data: nil) let task = URLSession.shared.dataTask(with: request) { data, response, error in if(error != nil) { result.message = "Fail Error not null : \(error.debugDescription)" } else { result.message = "Success" result.data = data } finish(result) } task.resume() }usage:in my VClet dict:[String:String] = ["username": view.emailField.text ?? "", "password": view.passField.text ?? "", "grant_type": "password"] let url = URL(string: “example”)! NetworkManager.formData(url: url, params: dict) { (message, data) in print(message) print(data) didn't work either it says Mising grant_typethird way:public static func LoginGenerateTokenPOST(userName: String, password: String, completion: @escaping (Bool) -&gt; ()) { let baseUrl = "example" let url = URL(string: "\(baseUrl)example")! var request = URLRequest(url: url) request.setValue("application/form-data", forHTTPHeaderField: "Content-Type") //request.setValue("application/json", forHTTPHeaderField: "Accept") request.setValue("example_api", forHTTPHeaderField: "example_api_password") request.httpMethod = "POST" let postString = "username=\(userName.lowercased())&amp;password=\(password.sha256())&amp;grant_type=password" request.httpBody = postString.data(using: .utf8) let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error completion(false) print("error") return } if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors print("statusCode should be 200, but is \(httpStatus.statusCode)") completion(false) } do { if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary { print(convertedJsonIntoDict) } } catch let error as NSError { completion(false) print(error.localizedDescription) } } task.resume() }this is my third function didn't work eitherso my question is:what is the best way to use basic auth URLSession POST, what did i do wrong in any of the 3 cases?, or all 3 are useless
3
0
5.8k
Jun ’20
Expanding Table View Cells index out of range
im trying to make an expandable table view inside of viewCellimport UIKit class TableSupportVC: UITableViewController { let interface: TableSupportView = { let interface = TableSupportView(frame: CGRect.zero) interface.translatesAutoresizingMaskIntoConstraints = false return interface }() struct cellData { var opened = Bool() var title = String() var sectionData = [String]() } struct dataInside { var opened = Bool() var title = String() var info = [String]() } var tableViewData = [cellData]() var tableViewDataInside = [dataInside]() override func viewDidLoad() { super.viewDidLoad() //register tables tableView.register(TableSupportCell.self, forCellReuseIdentifier: menuCellIdita) tableView.register(TableSupportSubtitleCell.self, forCellReuseIdentifier: menuCellda) // Heres my data for cells tableViewData = [cellData(opened: false, title: "1", sectionData: ["1.1", "1.2","1.3","1.4"]), cellData(opened: false, title: "2", sectionData: ["2.1", "2.2", "2.3"]) ] tableViewDataInside = [dataInside(opened: false, title: "1.1.1", info: ["1.1.1"])] setThemeNavigationBar() // Size Scrollview interface.scrollView.contentSize = CGSize(width: wScreen, height: hScreen * 1.40) initComponents() } func setThemeNavigationBar() { let navigationBarAppearace = UINavigationBar.appearance() navigationBarAppearace.tintColor = blueBlumon navigationBarAppearace.barTintColor = blueBlumon navigationController?.navigationBar.barTintColor = blueBlumon navigationController?.navigationBar.barStyle = .blackOpaque navigationController?.navigationBar.isTranslucent = false } private func initComponents() { setNavItems() setSubviews() setAutolayout() } private func setSubviews() { view.backgroundColor = UIColor.white view.addSubview(interface) } private func setNavItems() { let backIcon = UIImage(named: "whiteArrow") let backItem = UIBarButtonItem(image: backIcon?.withRenderingMode(.alwaysTemplate), style: UIBarButtonItem.Style.plain, target: self, action: #selector(backPressed)) backItem.tintColor = UIColor.white navigationItem.leftBarButtonItem = backItem let logoIcon = UIImage(named: "itemLogoBlue") let logoItem = UIBarButtonItem(image: logoIcon?.withRenderingMode(.alwaysOriginal), style: UIBarButtonItem.Style.plain, target: nil, action: nil) navigationItem.rightBarButtonItem = logoItem } // Método para definir el autolayout de los componentes de la vista principal del controlador private func setAutolayout() { NSLayoutConstraint.activate([ interface.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), interface.trailingAnchor.constraint(equalTo: view.trailingAnchor), interface.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor), interface.leadingAnchor.constraint(equalTo: view.leadingAnchor) ]) } // Método de selector backPressed @objc private func backPressed() { self.navigationController?.popViewController(animated: true) dismiss(animated: true, completion: nil) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -&gt; Int { return tableViewData.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { if tableViewData[section].opened == true{ return tableViewData[section].sectionData.count + 1 } **//INDEX OUT OF RANGE HERE** if tableViewDataInside[section].opened == true{ return tableViewDataInside[section].info.count + 1 } else { return 1 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell { if indexPath.row == 0{ let cell = tableView.dequeueReusableCell(withIdentifier: menuCellIdita, for: indexPath) as! TableSupportCell cell.optionTitle.text = tableViewData[indexPath.section].title return cell } if indexPath.row == 2 &amp;&amp; tableViewData[indexPath.section].title == "1.2"{ let cell = tableView.dequeueReusableCell(withIdentifier: menuCellda, for: indexPath) as! TableSupportSubtitleCell cell.title.text = tableViewDataInside[indexPath.section].title //cell.subtitle.text = tableViewDataInside[indexPath.section].info return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: menuCellIdita, for: indexPath) as! TableSupportCell cell.optionTitle.text = tableViewData[indexPath.section].sectionData[indexPath.row - 1] return cell } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("el indexpath es: \(indexPath.row)") if indexPath.row == 0 { if tableViewData[indexPath.section].opened == true{ tableViewData[indexPath.section].opened = false let sections = IndexSet.init(integer: indexPath.section) tableView.reloadSections(sections, with: .none) } else{ tableViewData[indexPath.section].opened = true let sections = IndexSet.init(integer: indexPath.section) tableView.reloadSections(sections, with: .none) } } if indexPath.row == 2 &amp;&amp; tableViewData[indexPath.section].title == "1.2"{ if tableViewDataInside[indexPath.section].opened == true{ tableViewDataInside[indexPath.section].opened = false let sections = IndexSet.init(integer: indexPath.section) tableView.reloadSections(sections, with: .none) } else{ tableViewDataInside[indexPath.section].opened = true let sections = IndexSet.init(integer: indexPath.section) tableView.reloadSections(sections, with: .none) } } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -&gt; CGFloat { return 80 } }as you can see every time the user selects certain cells it activateoverride func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.row == 0 {if user press row 0 it will activate the codesame case foroverride func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {but when i try to setoverride func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {and run it crash index out of rangethe main problem: i cant show my other cell *tableViewDataInside*when the user clicks for example 1.2
4
0
798
Mar ’20
How to handle URLSession.shared.dataTask properly
Hi developers im having some issue or misplaced tasksso i had to develop a framework with some functionsthis is my main FUNCTION where the issue began func saveDataDevice(idPos: String, macAddress: String) { // this first function obtains the MAIN token for further tasks == 'tokenForTransaction' let value = FirstInitDevice.tokentransaccional(username: idPos) //now i'd 2 seconds timer after tokentransaccional is launched DispatchQueue.main.asyncAfter(deadline: .now() + 2.0, execute: { //after obtain tokenForTransaction i can do any WS, deviceInitWsCall gets call now it returns 'PosId' //after finish the task so i'd save it for further fuctions let value2 = FirstInitDevice.deviceInitWsCall(serialNumber: idPos) let posidd = value2.PosId let convert = String(posidd) UserDefaults.standard.set(convert, forKey: "PosId") //now i can do the third function using PosId parameter and obtain 'rsa' //this is where the trouble shows for the first time, because the application hasn't finish the past task //FirstInitDevice.deviceInitWsCall is not done yet that's why my if == "" just in case ill show the error immediately let value3 = FirstInitDevice.getKeyWS(posId: value2.PosId) LoginSingleton.shared.pos_id = value2.PosId if value3.rsa == "" { let alert = UIAlertController(title: "alert", message: "Cannot init KEYS", preferredStyle: UIAlertController.Style.alert) let action = UIAlertAction(title: "OK", style: UIAlertAction.Style.destructive, handler: nil) alert.addAction(action) self.present(alert, animated: true, completion: nil) }else { // if not continue //decrypt rsa data let rsaData = RSA().getRSAData(publicKeyHex: value3.rsa) keysSingleton.shared.tk = rsaData.tk //func 4 runs after decrypt is done BUT is not, because third function is not over yet let value4 = FirstInitDevice.callInitDukptKeys(pos_id: value2.PosId, rsa: rsaData.rsa, check_value: rsaData.checkValue, crc32: rsaData.crc32) //same IF just in case == "" if value4.ksnString == ""{ let alert = UIAlertController(title: "Alert", message: "Cannot init KEYS", preferredStyle: UIAlertController.Style.alert) let action = UIAlertAction(title: "OK", style: UIAlertAction.Style.destructive, handler: nil) alert.addAction(action) self.present(alert, animated: true, completion: nil) } else{ keysSingleton.shared.ksn = value4.ksnString keysSingleton.shared.new_key = value4.newKey keysSingleton.shared.tk = value4.ksnString self.doTransaction() } } }) }as you can see one functions leads to another and so and so, it doesn't work without getting the previous parameterfor some reason the applications saves the LAST obtained parameter INSTED the current one, this apply to any other function in the libraryi have tried1.- increasing the timer forDispatchQueue.main.asyncAfter(deadline: .now() + 8.0, execute: {2.- set for every function deadline 8s3.- set DispatchGroup() .enter .leave to every functionbut it didn't work, so the question leads to How can i handle URLSession.shared.dataTask after they finish properlythis are the functions on my libraryFIRST FUNCTION tokentransaccionalpublic static func tokentransaccional(username: String){ let baseUrl = "http://bla bla" let headers = [ "Authorization": "Basic bla bla" ] let url = URL(string: "bla bla")! var request = URLRequest(url: url) request.allHTTPHeaderFields = headers request.httpMethod = "POST" request.timeoutInterval = 60 request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Accept") let password = username+"bla bla" let postString = "bla bla" request.httpBody = postString.data(using: .utf8) let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error print("error=\(error)") return } if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors print("statusCode should be 200, but is \(httpStatus.statusCode)") print("response = \(response)") } do { if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary { let responseError = convertedJsonIntoDict["error"] as? String let errorDescription = convertedJsonIntoDict["error_description"] as? String if responseError?.count == nil { let tokenAcceso = convertedJsonIntoDict["access_token"] as? String LoginSingleton.shared.tokenForTransaction = tokenAcceso ?? "" UserDefaults.standard.set(tokenAcceso, forKey: "AccessTokenLogin") } else { print("error") } } } catch let error as NSError { print("catch let error") print(error.localizedDescription) } } task.resume() }second function deviceInitWsCallpublic static func deviceInitWsCall(serialNumber: String) -&gt; (PosId: Int, transaction_profile: String) { let token = UserDefaults.standard.string(forKey: "AccessTokenLogin") ?? "" let headers = [ "Authorization": "bla bla" ] let baseUrl = "bla bla" let portBPC = "bla bla" let deviceInitWsPoint = "bla bla" let Url = String(format: "bla bla") let serviceUrl = URL(string: Url) let parameterDictionary = ["bla bla": serialNumber] var request = URLRequest(url: serviceUrl!) request.httpMethod = "POST" request.allHTTPHeaderFields = headers request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") let httpBody = try? JSONSerialization.data(withJSONObject: parameterDictionary, options: []) request.httpBody = httpBody let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print("error=\(error)") return } if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { print("statusCode should be 200, but is \(httpStatus.statusCode)") print("response = \(response)") } do { if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary { print(convertedJsonIntoDict) let response = convertedJsonIntoDict let status = response["status"] as? Bool if status == true { UserDefaults.standard.set(response, forKey: "deviceInitDictionary") let mainResponse = response["dataResponse"] as! NSDictionary let getPosId = mainResponse["posId"] as! Int UserDefaults.standard.set(getPosId, forKey: "getPosId") let getQps = mainResponse["qps"] as! Bool let getTransactionProfile = mainResponse["transactionProfile"] as! String UserDefaults.standard.set(getTransactionProfile, forKey: "getTransactionProfile") let dataContact = mainResponse["contact"] as! NSDictionary let indicatorPartialCancellation = mainResponse["partialCancellation"] as? Bool LoginSingleton.shared.qps = getQps UserDefaults.standard.set(getQps, forKey: "getQps") LoginSingleton.getInstance().pos_id = getPosId dataPresentReatailPresent.shared.posId = getPosId LoginSingleton.getInstance().qps = getQps LoginSingleton.getInstance().transaction_profile = getTransactionProfile LoginSingleton.getInstance().partialCancellation = indicatorPartialCancellation ?? false } else{ print("error") } } } catch let error as NSError { print("catch let error") print(error.localizedDescription) } }.resume() let PosId = UserDefaults.standard.integer(forKey: "getPosId") let transaction_profile = UserDefaults.standard.string(forKey: "getTransactionProfile") ?? "" return (PosId, transaction_profile) }third function getKeyWSpublic static func getKeyWS(posId: Int) -&gt; (rsa: String, rsa_id: Int) { let token = UserDefaults.standard.string(forKey: "AccessTokenLogin") ?? "" let headers = [ "Authorization": "bla bla" ] let baseUrl = "bla bla" let portBPC = ":bla bla" let deviceGetKeyUrl = "bla bla" let Url = String(format: "bla bla") let serviceUrl = URL(string: Url) let parameterDictionary = ["bla bla": posId] var request = URLRequest(url: serviceUrl!) request.httpMethod = "POST" request.allHTTPHeaderFields = headers request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") let httpBody = try? JSONSerialization.data(withJSONObject: parameterDictionary, options: []) request.httpBody = httpBody let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print("error=\(error)") return } if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { print("statusCode should be 200, but is \(httpStatus.statusCode)") print("response = \(response)") } do { if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary { // Print out dictionary print(convertedJsonIntoDict) let response = convertedJsonIntoDict guard let MainDataResponse = response["dataResponse"] as? NSDictionary else { return } let rsa_id = MainDataResponse["rsaId"] as? Int ?? 0 let rsa = MainDataResponse["rsa"] as? String ?? "" UserDefaults.standard.set(rsa_id, forKey: "rsa_id") UserDefaults.standard.set(rsa, forKey: "rsa") } } catch let error as NSError { print("catch let error") print(error.localizedDescription) } }.resume() let rsa = UserDefaults.standard.string(forKey: "rsa") ?? "" let rsa_id = UserDefaults.standard.integer(forKey: "rsa_id") return (rsa, rsa_id) }fourth function callInitDukptKeyspublic static func callInitDukptKeys(pos_id: Int, rsa: String, check_value: String , crc32: String) -&gt; (newKey: String, ksnString: String, crc32: String, checkValue: String) { let token = UserDefaults.standard.string(forKey: "AccessTokenLogin") ?? "" let headers = [ "Authorization": "bla bla" ] let baseUrl = "bla bla" let portBPC = ":bla bla" let deviceInitDukptKeysUrll = "bla bla" let UUrl = String(format: "bla bla") let serviceUrlll = URL(string: UUrl) let parameterDictionary = ["bla bla": String(pos_id), "bla bla": rsa, "bla bla": check_value, "bla bla": crc32] var requests = URLRequest(url: serviceUrlll!) requests.httpMethod = "POST" requests.allHTTPHeaderFields = headers requests.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") requests.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") let httpBody = try? JSONSerialization.data(withJSONObject: parameterDictionary, options: []) requests.httpBody = httpBody _ = URLSession.shared.dataTask(with: requests) { data, response, error in guard let data = data, error == nil else { print("error=\(String(describing: error))") return } if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { print("statusCode should be 200, but is \(httpStatus.statusCode)") print("response = \(String(describing: response))") } do { if let DictConvert = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary { // Print out dictionary let response = DictConvert let status = response["status"] as? Bool if status == true { let mainResponse = response["dataResponse"] as? NSDictionary let getKey = mainResponse!["key"] as? String let keyCheckValue = mainResponse!["keyCheckValue"] as? String let keyCrc32 = mainResponse!["keyCrc32"] as? String let ksn = mainResponse!["ksn"] as? String print("valor getKey: \(getKey)") print("valor ksn: \(ksn)") print("valor keyCrc32: \(keyCrc32)") print("valor keyCheckValue: \(keyCheckValue)") UserDefaults.standard.set(getKey, forKey: "getKey") UserDefaults.standard.set(ksn, forKey: "ksn") UserDefaults.standard.set(keyCrc32, forKey: "keyCrc32") UserDefaults.standard.set(keyCheckValue, forKey: "keyCheckValue") } else { print("error") } } } catch let error as NSError { print("catch let error") print(error.localizedDescription) } }.resume() let newKey = UserDefaults.standard.string(forKey: "getKey") ?? "" let ksnString = UserDefaults.standard.string(forKey: "ksn") ?? "" let crc32 = UserDefaults.standard.string(forKey: "keyCrc32") ?? "" let checkValue = UserDefaults.standard.string(forKey: "keyCheckValue") ?? "" return (newKey, ksnString, crc32, checkValue) }
2
0
5.8k
Jan ’20
Static Func not calling variable
Hi developers, im doing a framework with this functionpublic func LoginGenerateToken(userName: String, password: String) { let parameters = LoginGenerateTokenStruct(userName: userName, password: password.sha256()) LoginSingleton.shared.mailUserLogin = userName networkManager1 = URL_Session() networkManager1?.delegate = self networkManager1?.LoginGenerateTokenPOST(parameters: parameters) }so when the user install the framework and call this function it should ask for 'userName' and 'password'but it doesn't because is not an static functionthe function get call like thisLoginWS.LoginGenerateToken()insted ofLoginWS.LoginGenerateToken(userName: String, password: String)i can't set static because im calling a delegate outside the func LoginGenerateTokennetworkManager1?.delegate = selfhow could i get the function to work without using static?this is the full code// // LoginWS.swift // IntegradorFrameWork // // Created by BlumonPay on 11/27/19. // Copyright © 2019 BlumonPay. All rights reserved. // import Foundation import CommonCrypto public class LoginWS: URL_SessionDelegate{ var networkManager1: URL_Session? func connectionFinishWithError(session: URL_Session, error: Error) { print(error) } func connectionFinishSuccessfull(session: URL_Session, response: NSDictionary) { print(response) let dictionaryValue = response as? NSDictionary let responseError = dictionaryValue?["error"] as? String let errorDescription = dictionaryValue?["error_description"] as? String if responseError?.count == nil { let dictionaryValue = response as? NSDictionary let tokenAcceso = dictionaryValue?["access_token"] as! String print("Access Token: \(tokenAcceso)") }else{ let responseError = dictionaryValue?["error"] as! String let errorDescription = dictionaryValue?["error_description"] as! String print("ERROR: \(errorDescription)") } } public func LoginGenerateToken(userName: String, password: String) { let parameters = LoginGenerateTokenStruct(userName: userName, password: password.sha256()) LoginSingleton.shared.mailUserLogin = userName networkManager1 = URL_Session() networkManager1?.delegate = self networkManager1?.LoginGenerateTokenPOST(parameters: parameters) } } extension String { func sha256() -&gt; String{ if let stringData = self.data(using: String.Encoding.utf8) { return hexStringFromData(input: digest(input: stringData as NSData)) } return "" } private func digest(input : NSData) -&gt; NSData { let digestLength = Int(CC_SHA256_DIGEST_LENGTH) var hash = [UInt8](repeating: 0, count: digestLength) CC_SHA256(input.bytes, UInt32(input.length), &amp;hash) return NSData(bytes: hash, length: digestLength) } private func hexStringFromData(input: NSData) -&gt; String { var bytes = [UInt8](repeating: 0, count: input.length) input.getBytes(&amp;bytes, length: input.length) var hexString = "" for byte in bytes { hexString += String(format:"%02x", UInt8(byte)) } return hexString } }delegate method@objcprotocol URL_SessionDelegate { func connectionFinishSuccessfull(session: URL_Session, response: NSDictionary) //Response del mismotipo que devuelve el JSON o utilizar any para cachar cualquiera de los 2 func connectionFinishWithError(session: URL_Session, error: Error) @objc optional func connectionFinishSuccessfull2(session: URL_Session, response: NSDictionary) @objc optional func connectionFinishSuccessfull3(session: URL_Session, response: NSDictionary) @objc optional func connectionFinishSuccessfull4(session: URL_Session, response: NSDictionary) } class URL_Session: NSObject, URLSessionDelegate, URLSessionDataDelegate { var dataTask: URLSessionDataTask? //Descarga los bytes, evalua la respuesta del servidor var responseData: Data = Data() //Respuesta del lado del servidor var httpResponse: HTTPURLResponse? static var delegate: URL_SessionDelegate? var delegat2: URL_SessionDelegate? var delegat3: URL_SessionDelegate? var delegat4: URL_SessionDelegate?
3
0
570
Nov ’19
how to disable Zoom-Out & Zoom-In
Hi developers is there any chanse to disable Zoom-Out &amp; Zoom-In in WkWebView?here's all my code so far keep in mind i'm only displaying a web in webView i don't have any other functions 😕import UIKit import WebKit class ViewController: UIViewController, WKNavigationDelegate { @IBOutlet var webView: WKWebView! override func viewDidLoad() { super.viewDidLoad() displayWebPage() let preferences = WKPreferences() preferences.javaScriptEnabled = true let configuration = WKWebViewConfiguration() configuration.preferences = preferences let webView = WKWebView(frame: .zero, configuration: configuration) // Do any additional setup after loading the view, typically from a nib. } private func displayWebPage() { let url = URL(string: "hee hee") let request = URLRequest(url: url!) webView.navigationDelegate = self webView.load(request) webView.sizeToFit() } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { print(error) } }
9
1
20k
Nov ’18