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
Reply to Official reference for "#available" in Swift language?
Can anybody tell me whether there is official reference? I would not say the official documentation of Swift (so called the Swift book) is easy to read, but there actually is. Availability Condition It is classified into Statements of the doc, maybe because it is only used inside conditional statements.
Topic: Programming Languages SubTopic: Swift Tags:
Replies
Boosts
Views
Activity
Sep ’21
Reply to Create ios Swift Framework independent of Xcode Compiler Version
Have you tried setting BUILD_LIBRARY_FOR_DISTRIBUTION? Library Evolution in Swift
Topic: Programming Languages SubTopic: Swift Tags:
Replies
Boosts
Views
Activity
Sep ’21
Reply to How to save the state of a Switch
You declare Settings_Custom_Cell (a very odd name as Swift code), but you are not using it in Settings. Have you really set up the storyboard for Settings to use the custom class Settings_Custom_Cell for the reuse identifier cell?
Topic: Programming Languages SubTopic: Swift Tags:
Replies
Boosts
Views
Activity
Sep ’21
Reply to I am creating a meditation app. I want to repeat the time to inhale and the time to exhale.
You should better respond to answers of another question of yours.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Replies
Boosts
Views
Activity
Sep ’21
Reply to Launch Screen Image
You should better clarify how you have set it up. As far as I tried, the image (200 x 200) is shown as the original size:
Topic: Programming Languages SubTopic: Swift Tags:
Replies
Boosts
Views
Activity
Sep ’21
Reply to How can I fix this leaking memory?
I have tried your code with Leaks and no memory leak is reported even if I tap the button hundreds of times. Can you clarify how you have checked it and how to reproduce the issue?
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Replies
Boosts
Views
Activity
Sep ’21
Reply to I am trying to customize the timer app made from books. I may not understand it, so let me ask you a question.
Please try this: var trueTimerValue: Int { timerValue * 60 } (No @State.)
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Replies
Boosts
Views
Activity
Sep ’21
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:
Replies
Boosts
Views
Activity
Sep ’21
Reply to Links in AttributedString Markdown fail to load
I cannot find any code to respond to taps on the UILabel, better search with "links in uilabel". Or else, using UITextView would be easier.
Topic: UI Frameworks SubTopic: UIKit Tags:
Replies
Boosts
Views
Activity
Sep ’21
Reply to Developing with a team -- how to set up?
You may need an Apple ID registered as an organization. https://developer.apple.com/support/app-account/ Or your members can use their own bundle id temporarily while developing. com.myUniqueName.com.kithrup.filterTest (need to care not to commit or push the temporary bundle id.)
Replies
Boosts
Views
Activity
Sep ’21
Reply to Closure containing a declaration cannot be used with result builder 'ViewBuilder' and Struct 'ViewBuilder' declared here (SwiftUI.ViewBuilder)
Missing closing braces (}) is causing the issue. So, it is very important what are // some code.... Please show enough code.
Topic: Programming Languages SubTopic: Swift Tags:
Replies
Boosts
Views
Activity
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:
Replies
Boosts
Views
Activity
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:
Replies
Boosts
Views
Activity
Sep ’21
Reply to New SwiftUI Project Won't Compile and Show Live Preview
Your Xcode looks broken. Have you installed the Xcode from Mac App Store using the right Mac?
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Replies
Boosts
Views
Activity
Aug ’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:
Replies
Boosts
Views
Activity
Aug ’21