Post

Replies

Boosts

Views

Activity

Reply to Read a text file with swift
Sometimes error message appears: "The file "Text.strings" couldn't be opened using text encoding Unicode (UTF-8)." Sometimes the text is shown in strange format. Why? strings is not a good extension to embed text files into an Xcode project. It may be treated as a Localized string file and may be compiled into some other format than plain text while building your project. Please try renaming the text resource to Text.txt and see what happens.
Topic: Programming Languages SubTopic: Swift Tags:
Sep ’21
Reply to App crashing while using collection view
Please use Code Block when you show some code: import UIKit class ViewController: UIViewController { @IBOutlet var collectionView: UICollectionView! @IBOutlet var topCollectionView: UICollectionView! @IBOutlet weak var Leading: NSLayoutConstraint! @IBOutlet weak var Trailing: NSLayoutConstraint! @IBOutlet private weak var Menubutton: UIButton! var menuOut = false override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. //self.navigationItem.titleView = UIImageView(image: UIImage(named: "Logo")) collectionView.register(MiddleCollectionViewCell.nib(), forCellWithReuseIdentifier: MiddleCollectionViewCell.identifier) collectionView.delegate=self collectionView.dataSource=self topCollectionView.register(CircleCollectionViewCell.self, forCellWithReuseIdentifier: CircleCollectionViewCell.identifier) topCollectionView.delegate=self topCollectionView.dataSource=self // Menu // start let destructiveAction = UIAction(title: "Delete",image: UIImage(systemName: "nosign") , attributes: .destructive) { (_) in print("Delete") } let menu = UIMenu(title: "", children: [ UIAction (title: "Add New", image: UIImage(systemName: "plus.circle"), handler: { _ in }), UIAction (title: "Manage", image: UIImage(systemName: "hammer"), handler: { _ in }), destructiveAction ]) self.Menubutton.menu = menu // Menu end } // Menu animation @IBAction func MenuTap(_ sender: Any) { if menuOut == false { Leading.constant = -150 Trailing.constant = 150 menuOut = true } else{ Leading.constant = 0 Trailing.constant = 0 menuOut = false } UIView.animate(withDuration: 0.2, delay: 0.0 , options: .curveEaseIn,animations: { self.view.layoutIfNeeded() }){(animationComplete) in print("Animation Completed") } } // Menu animation ends } // used for upper collection view extension ViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.deselectItem(at: indexPath, animated: true ) print("btn tapped") } } extension ViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 12 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MiddleCollectionViewCell.identifier, for: indexPath) as! MiddleCollectionViewCell let topcell = collectionView.dequeueReusableCell(withReuseIdentifier: CircleCollectionViewCell.identifier, for: indexPath) as! CircleCollectionViewCell topcell.configure(with: "") cell.configure(with: UIImage(named: "four")!) return cell; topcell } } //extension ViewController: UICollectionViewDelegateFlowLayout { // //} You register CircleCollectionViewCell.self only for topCollectionView. So, calling collectionView.dequeueReusableCell(withReuseIdentifier: CircleCollectionViewCell.identifier, for: indexPath) causes the error when called where collectionView is not topCollectionView. You cannot return two things from a single return statement, return cell; topcell does not make sense and ; topcell is ignored. (You should better not ignore the warnings shown by Xcode.) You may need to check if collectionView is topCollectionView or not inside delegate methods: func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if collectionView === self.topCollectionView { let topcell = collectionView.dequeueReusableCell(withReuseIdentifier: CircleCollectionViewCell.identifier, for: indexPath) as! CircleCollectionViewCell topcell.configure(with: "") return topcell } else { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MiddleCollectionViewCell.identifier, for: indexPath) as! MiddleCollectionViewCell cell.configure(with: UIImage(named: "four")!) return cell } }
Topic: Programming Languages SubTopic: Swift Tags:
Sep ’21
Reply to Can't read 'data' object returned from URLRequest
Your code goes through to print("FDC Data Fetch Failed:...) even when if let data = data is working as expected, when try? ends with nil. Generally I do not recommend to use try? where you do not understand all the possibilities when error is thrown. Use do-try-catch and never use try?. Please try something like this and consider what is causing the problem: let API_Key: String = "..." // You should not make API_Key public. let fdcFoodItemSearchKeywords: String = "apple%20fuji" let fdcResourceString = "https://api.nal.usda.gov/fdc/v1/foods/search?api_key=\(API_Key)&query=\(fdcFoodItemSearchKeywords)&dataType=Foundation" guard let fdcResourceURL = URL(string: fdcResourceString) else { print("Invalid URL") return } var request = URLRequest(url: fdcResourceURL) request.addValue("application/json", forHTTPHeaderField: "Accept") request.httpMethod = "GET" print("The request variable = \(request.description)") print("The request variable http Header is: \(String(describing: request.allHTTPHeaderFields))") URLSession.shared.dataTask(with: request) { data, response, error in if let error = error { print("FDC Data Fetch Failed: \(error)") return } guard let data = data else { print("data is nil") return } print("The data has \(data.count) bytes and is: \n") let responseText = String(data: data, encoding: .utf8) ?? "*unknow encoding*" print("The response is: \(responseText)") do { let decodedResponse = try JSONDecoder().decode(FDCResponse.self, from: data) DispatchQueue.main.async { self.FDCResults = decodedResponse.FDCResults } return } catch { print("FDC Data Decoding Failed: \(error)") } }.resume()
Topic: App & System Services SubTopic: General Tags:
Sep ’21
Reply to DateFormatter - String to Date
I just need the get the date string, convert it to the format MM dd, yyyy - hh:mm How can I do it ? You may need another DateFormatter to convert it to the format MM dd, yyyy - hh:mm: struct MyView: View { //this value is coming from a JSON @State var myDate = "3000-01-01T08:00:00-08:00" let myDateFormatter: DateFormatter = { let df = DateFormatter() df.locale = Locale(identifier: "en_US_POSIX") df.dateFormat = "MM dd, yyyy - hh:mm" df.timeZone = TimeZone.current return df }() var body: some View { Text("\(formatDate(dateString: myDate), formatter: myDateFormatter)") } }
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Aug ’21