Post

Replies

Boosts

Views

Activity

Reply to UIImage.init - imageLiteralResourceName crashing during App review
So, I assume you use some code like this: func getCurrrentDayNumber() -> String { let currentDateTime = Date(); let formatter = DateFormatter(); formatter.timeStyle = .none; formatter.dateStyle = .long; let dateTimeString = formatter.string(from: currentDateTime); var dayNumber = dateTimeString.split(separator: " "); dayNumber = dayNumber[1].split(separator: ","); return String(dayNumber[0]); } Frankly saying, this is a super bad implementation to get the day number (1...31). I do not know which languages your app would support, but your getCurrrentDayNumber() returns August when region is set to United Kingdom even when Language is set to en. I believe that would cause the error you described. Please try something like this: func getCurrrentDayNumber() -> String { let currentDateTime = Date() var gregorianCalendar = Calendar(identifier: .gregorian) gregorianCalendar.timeZone = TimeZone.current let dateComponents = gregorianCalendar.dateComponents([.day], from: currentDateTime) return String(dateComponents.day!) } Generally, you should better not rely on the String generated by DateFormatter.Style.long.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Aug ’21
Reply to MatchedGeometryEffect SwiftUI
I have not played with matchedGeometryEffect yet, so read the followings as as far as I tried things. There may be other better ways. Text, is duplicated during the transition You have two Texts, and with using matchedGeometryEffect, they both are animated. Applying matchedGeometryEffect after frame is specified, the positions of the two in animation are different. Please try moving matchedGeometryEffect before frame. when I press again to get it back to its original position, no animation takes place Seems some sort of symmetry is needed to trigger animation when you set numberViewModel.tapped to false. Please try something like this: struct NumberView: View { @ObservedObject var numberViewModel: NumberViewModel var animation: Namespace.ID var number: Number var body: some View{ GroupBox{ if numberViewModel.selected.number != number.number { Text("\(number.number)") .font(.largeTitle) .matchedGeometryEffect(id: number.number, in: animation) //<- .frame(width: 100, height: 100, alignment: .center) } } } } struct NumberTappedView: View { var animation: Namespace.ID @ObservedObject var numberViewModel: NumberViewModel var body: some View{ GroupBox { if numberViewModel.tapped { //<- Text("\(numberViewModel.selected.number)") .font(.largeTitle) .matchedGeometryEffect(id: numberViewModel.selected.number, in: animation) //<- .frame(width: 200, height: 200, alignment: .center) } //<- } } } Or you would prefer this version of NumberTappedView: struct NumberTappedView3: View { var animation: Namespace.ID @ObservedObject var numberViewModel: NumberViewModel var body: some View{ GroupBox { if numberViewModel.tapped { ZStack { ForEach(numbers) { number in if numberViewModel.selected.number == number.number { Text("\(numberViewModel.selected.number)") .font(.largeTitle) .matchedGeometryEffect(id: numberViewModel.selected.number, in: animation) .frame(width: 200, height: 200, alignment: .center) } } } } } } }
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Aug ’21
Reply to Showing Decimal value
Unfortunately, the String interpolation of LocalizedStringKey using specifier: requires the value conform to _FormatSpecifiable, to which Decimal does not. See LocalizedStringKey.StringInterpolation. String interpolation of String does not support interpolation using specifier:. See DefaultStringInterpolation. You can use a String interpolation of LocalizedStringKey using formatter: with value of NSDecimalNumber: struct ContentView: View { let myFormatter: NumberFormatter = { let nf = NumberFormatter() nf.maximumFractionDigits = 2 nf.minimumFractionDigits = 2 return nf }() @State var myVariable: Decimal = Decimal(string: "66.67")! var body: some View { Text("\(myVariable as NSDecimalNumber, formatter: myFormatter)") } } If Decimal operation is not important for your app, using Double (which conforms to _FormatSpecifiable) might be a good option. Or you can customize the behavior of String interpolation of LocalizedStringKey, but I'm not sure if it would be a good option.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
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:
Aug ’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 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 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 UIImage.init - imageLiteralResourceName crashing during App review
Better show your code well-formatted. As the editing functionality is very limited in this site, you can use Your Answer to show some additional information. And = after return causes error...
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Replies
Boosts
Views
Activity
Aug ’21
Reply to UIImage.init - imageLiteralResourceName crashing during App review
So, I assume you use some code like this: func getCurrrentDayNumber() -> String { let currentDateTime = Date(); let formatter = DateFormatter(); formatter.timeStyle = .none; formatter.dateStyle = .long; let dateTimeString = formatter.string(from: currentDateTime); var dayNumber = dateTimeString.split(separator: " "); dayNumber = dayNumber[1].split(separator: ","); return String(dayNumber[0]); } Frankly saying, this is a super bad implementation to get the day number (1...31). I do not know which languages your app would support, but your getCurrrentDayNumber() returns August when region is set to United Kingdom even when Language is set to en. I believe that would cause the error you described. Please try something like this: func getCurrrentDayNumber() -> String { let currentDateTime = Date() var gregorianCalendar = Calendar(identifier: .gregorian) gregorianCalendar.timeZone = TimeZone.current let dateComponents = gregorianCalendar.dateComponents([.day], from: currentDateTime) return String(dateComponents.day!) } Generally, you should better not rely on the String generated by DateFormatter.Style.long.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Replies
Boosts
Views
Activity
Aug ’21
Reply to MatchedGeometryEffect SwiftUI
I have not played with matchedGeometryEffect yet, so read the followings as as far as I tried things. There may be other better ways. Text, is duplicated during the transition You have two Texts, and with using matchedGeometryEffect, they both are animated. Applying matchedGeometryEffect after frame is specified, the positions of the two in animation are different. Please try moving matchedGeometryEffect before frame. when I press again to get it back to its original position, no animation takes place Seems some sort of symmetry is needed to trigger animation when you set numberViewModel.tapped to false. Please try something like this: struct NumberView: View { @ObservedObject var numberViewModel: NumberViewModel var animation: Namespace.ID var number: Number var body: some View{ GroupBox{ if numberViewModel.selected.number != number.number { Text("\(number.number)") .font(.largeTitle) .matchedGeometryEffect(id: number.number, in: animation) //<- .frame(width: 100, height: 100, alignment: .center) } } } } struct NumberTappedView: View { var animation: Namespace.ID @ObservedObject var numberViewModel: NumberViewModel var body: some View{ GroupBox { if numberViewModel.tapped { //<- Text("\(numberViewModel.selected.number)") .font(.largeTitle) .matchedGeometryEffect(id: numberViewModel.selected.number, in: animation) //<- .frame(width: 200, height: 200, alignment: .center) } //<- } } } Or you would prefer this version of NumberTappedView: struct NumberTappedView3: View { var animation: Namespace.ID @ObservedObject var numberViewModel: NumberViewModel var body: some View{ GroupBox { if numberViewModel.tapped { ZStack { ForEach(numbers) { number in if numberViewModel.selected.number == number.number { Text("\(numberViewModel.selected.number)") .font(.largeTitle) .matchedGeometryEffect(id: numberViewModel.selected.number, in: animation) .frame(width: 200, height: 200, alignment: .center) } } } } } } }
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Replies
Boosts
Views
Activity
Aug ’21
Reply to Showing Decimal value
Unfortunately, the String interpolation of LocalizedStringKey using specifier: requires the value conform to _FormatSpecifiable, to which Decimal does not. See LocalizedStringKey.StringInterpolation. String interpolation of String does not support interpolation using specifier:. See DefaultStringInterpolation. You can use a String interpolation of LocalizedStringKey using formatter: with value of NSDecimalNumber: struct ContentView: View { let myFormatter: NumberFormatter = { let nf = NumberFormatter() nf.maximumFractionDigits = 2 nf.minimumFractionDigits = 2 return nf }() @State var myVariable: Decimal = Decimal(string: "66.67")! var body: some View { Text("\(myVariable as NSDecimalNumber, formatter: myFormatter)") } } If Decimal operation is not important for your app, using Double (which conforms to _FormatSpecifiable) might be a good option. Or you can customize the behavior of String interpolation of LocalizedStringKey, but I'm not sure if it would be a good option.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Replies
Boosts
Views
Activity
Aug ’21
Reply to Showing Decimal value
(The site was malfunctioning, removed.)
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
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 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 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 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 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 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 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 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 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