Post

Replies

Boosts

Views

Activity

Using String Catalog for Word Iteration/Partial Translation
I want to make use of String Catalog for some words that show the differences between countries like the USA and Canada. For example, I added both languages to my string catalog and I would like to have: Enter your Zip Code [English] Enter your Providence [English (Canada)] If I run the app without any change in the tables, I see all values shown correctly, but when I make this 1 word change in required field, all other strings start showing their keys instead of base values that are already in English language. What is the easiest way to achieve this using String Catalogs other than copy/pasting all the values from English table to English (Canada) table? I don't want to or need to translate all the strings in the catalog since they are literally the same, all I need is having iterations for some words.
0
1
489
Mar ’24
Building Error after updating to Xcode 14.3, now can't build even with 14.2
Yesterday I have updated to Xcode 14.3 (14E222b) and randomly my project stopped building giving this error: /path/libBarcodeScanner.a(msi.o), building for iOS Simulator, but linking in object file built for iOS, file /path/libBarcodeScanner.a' for architecture arm64. I have tried these solutions, which didn't help at all: Clean DerivedData and Build Run Xcode on Rosetta Exclude Architectures → Any iOS Simulator SDK → arm64 Build Active Architecture Only → Already set Yes for Debug Delete everything related to Xcode, and downgrade to Xcode 14.2. I literally can't work right now because of this random error... Any help would be appreciated.
5
1
7.0k
Apr ’23
Presenting AVPlayerViewController Embedded Inside UIViewController
Hi all. I'm trying to create custom controls for AVPlayer and managed to do it. Last thing I want to achieve is making the player go full screen while it is in-line mode, inside UICollectionViewCell, on device rotation. I'm using this code to present the player in full screen: override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {   super.viewWillTransition(to: size, with: coordinator)   collectionView?.collectionViewLayout.invalidateLayout()       let sourceVC = self   let destinationVC = LandscapePlayerViewController() // LandscapePlayerViewController also in view hierarchy within UICollectionViewCell   destinationVC.modalPresentationStyle = .fullScreen   sourceVC.present(destinationVC, animated: true) } This does the trick, but for some reason the player presents empty. It doesn't pass the playing video to presented full screen player. Any suggestions? Thank you!
0
0
733
Mar ’22
WidgetKit (Intent) - How to link multiple dynamic intents fetched from remote?
I'm creating a widget for my application and successfully added intent configuration with dynamic data that I got from API. This snippet gets the list and returns it to Intent: func provideLeagueOptionsCollection(for intent: LeagueConfigurationIntent, with completion: @escaping (INObjectCollection<LeagueType>?, Error?) -> Void) { request(for: Leagues.self, completion: { leagueList in let leagues = leagueList as! Leagues let activeLeagues = leagues.leagueList.map { (league: League) -> LeagueType in LeagueType(identifier: league.id, display: league.name) } let collection = INObjectCollection(items: activeLeagues) completion(collection, nil) }) } What I want to add is, when the user selects anything from this list, I want to show another option to select, it goes something like that: User selects League. Intent fetches Teams data from API with League's id provided on selection before and team list selection gets visible. User selects a team from the second list. Intent returns this data to IntentTimelineProvider -> getTimeline() The widget shows the selected team's stats. I tried to debug step-by-step, but after the first selection, none of these ConfigurationIntentHandling functions gets called. func provideTeamOptionsCollection(for intent: TeamConfigurationIntent, with completion: @escaping (INObjectCollection<TeamType>?, Error?) -> Void) { ... } func provideLeagueOptionsCollection(for intent: LeagueConfigurationIntent, with completion: @escaping (INObjectCollection<LeagueType>?, Error?) -> Void) { ... } // This method only gets called when interacted with League opiton in configuration view (not after selection from data list). override func handler(for intent: INIntent) -> Any { return self } // This method only gets called when the configuration menu shows up. My goal is to filter teams from a selected league, so the user won't have to scroll through a long list of teams. Also open for another suggestions beside this approach.
0
0
782
Feb ’22
How to get Body Fat Percentage data from HealthKit?
I'm trying to create a widget for myself so I can see my measurements on the screen. I successfully get Body Mass and Body Mass Index data from HealthKit, but my code doesn't work for fetching the Body Fat Percentage data. Couldn't find anything about Body Fat Percentage on my search, so I wanted to ask if I need to use a different way to fetch its data? Function for fetching the data: class func getMostRecentSample(for sampleType: HKSampleType, completion: @escaping (HKQuantitySample?, Error?) -> Swift.Void) { let mostRecentPredicate = HKQuery.predicateForSamples(withStart: Date.distantPast, end: Date(), options: .strictEndDate) let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false) let limit = 1 // This step won't execute as usual while working for Body Fat Percentage data; let sampleQuery = HKSampleQuery(sampleType: sampleType, predicate: mostRecentPredicate, limit: limit, sortDescriptors: [sortDescriptor]) { (query, samples, error) in DispatchQueue.main.async { guard let samples = samples, let mostRecentSample = samples.first as? HKQuantitySample else { completion(nil, error) return } completion(mostRecentSample, nil) } } HKHealthStore().execute(sampleQuery) // then jumps to here. } Function for getting the string from the fetched data: class func getSamples(for sampleType: HKSampleType, unit: HKUnit, completion: @escaping (String?, Error?) -> Swift.Void) { getMostRecentSample(for: sampleType) {(sample, error) in guard let sample = sample else { return } let BMI = String(sample.quantity.doubleValue(for: unit)) // let weight = String(sample.quantity.doubleValue(for: unit)) // let fatPercentage = String(sample.quantity.doubleValue(for: unit)) completion(BMI, nil) } } Sending the data to Timeline then preview it: func getTimeline(in context: Context, completion: @escaping (Timeline<WeightEntry>) -> Void) { let currentDate = Date() let refreshDate = Calendar.current.date(byAdding: .day, value: 1, to: currentDate)! guard let bodyMass = HKObjectType.quantityType(forIdentifier: .bodyMass), let bodyMassIndex = HKObjectType.quantityType(forIdentifier: .bodyMassIndex), let bodyFatPercentage = HKObjectType.quantityType(forIdentifier: .bodyFatPercentage) else { return } ProfileDataStore.getSamples(for: bodyMassIndex,unit: HKUnit.count()) { (sample, error) in guard let sample = sample else { return } let entry = WeightEntry(date: currentDate, value: sample) let timeline = Timeline(entries: [ entry ], policy: .after(refreshDate)) completion(timeline) } }
0
0
962
Oct ’21
How to use different content in same timeline?
I am creating a widget for my application. For the large size of the widget, I want to show 4 cells with different content that I fetch from an API call. But I couldn't manage to do it. This is how my widget looks like currently: Should I create a different entry struct for every cell? Or is there a way to put array/list in the entry struct and append 4 data to that entry from I got from the request? Does TimelineEntry have subscripts I can use? Like, entry[0].title Any suggestions about how can I achieve this? My entry struct: struct NewsEntry: TimelineEntry { var date: Date let configuration: ConfigurationIntent let header: String let imageUrl: String } My getTimeline function: func getTimeline(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (Timeline<Entry>) -> ()) { var entries: [NewsEntry] = [] let currentDate = Date() let later = Calendar.current.date(byAdding: .minute, value: 5, to: Date())! NewsProvider.request() { (data, error) in guard let data = data else { if let error = error { print(error) } return } let entry = NewsEntry(date: currentDate, configuration: configuration, header: data[0].title!, imageUrl: data[0].imageUrlDetail!) entries.append(entry) let timeline = Timeline(entries: entries, policy: .after(later)) completion(timeline) } } My EntryView: struct WidgetEntryView : View { var entry: Provider.Entry @Environment(\.widgetFamily) var widgetFamily var body: some View { VStack(alignment: .trailing, spacing: 6) { Image("logo") .frame(maxWidth: .infinity, alignment: .leading) if widgetFamily == .systemLarge { var columns: [GridItem] = Array(repeating: .init(), count: 2) LazyVGrid(columns: columns) { ForEach((0..<4)) { index in ZStack (alignment: .bottomLeading) { if let url = URL(string: entry.imageUrl), let imageData = try? Data(contentsOf: url), let uiImage = UIImage(data: imageData) { Image(uiImage: uiImage) .centerCropped() .frame(maxHeight: 150, alignment: .center) .cornerRadius(10) .overlay(RoundedRectangle(cornerRadius: 10) .stroke(Color.gray, lineWidth: 1)) .shadow(radius: 10) } else { Image("ph_background") .centerCropped() .frame(maxHeight: 150, alignment: .center) .cornerRadius(10) .overlay(RoundedRectangle(cornerRadius: 10) .stroke(Color.gray, lineWidth: 1)) .shadow(radius: 10) } Text(entry.header) .font(.system(size: 12)) .foregroundColor(.white) .fontWeight(.light) // .frame(maxHeight: 50) .background(Rectangle().fill(Color.black).blur(radius: 20)) .padding(.bottom, 5) .padding(.leading, 5) .padding(.trailing, 5) .padding(.top, 5) } } .frame(height: 160) } } } .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity) .padding() .background(LinearGradient(gradient: Gradient(colors: [Color(red:0.2, green:0.2, blue:0.2), .black]), startPoint: .top, endPoint: .bottom)) } }
1
0
904
Sep ’21
Unable to Dequeue Registered CollectionViewCells
Searched here and there but I couldn't find anything that I haven't already tried to fix my issue, so going to ask it again. I am trying to use a collection view with custom cells. The main collection view is in the Main View Controller. I'm using a generic cell named GenericHomeCollectionViewCell, then customize another collection view that it has. This cell doesn't have any issue with registering and dequeuing. (It might sound weird but I already have an application with this usage and it works without any problem, so I wanted to use the same method again.) The crash happens when I try to register and dequeue cells inside that generic cell. I have 4 different custom cells for use which are registered in awakeFromNib(). GenericHomeCollectionViewCell.swift override func awakeFromNib() { super.awakeFromNib() newsCollectionView.register(UINib(nibName: "HeadlineNewsCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "HeadlineNewsCollectionViewCell") newsCollectionView.register(UINib(nibName: "HomeAuthorCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "HomeAuthorCollectionViewCell") newsCollectionView.register(UINib(nibName: "NewsListCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "NewsListCollectionViewCell") newsCollectionView.register(UINib(nibName: "HomeDetailedNewCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "HomeDetailedNewCollectionViewCell") newsCollectionView.delegate = self newsCollectionView.dataSource = self } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if sectionType == .swipe { let cell : HeadlineNewsCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "HeadlineNewsCollectionViewCell", for: indexPath) as! HeadlineNewsCollectionViewCell cell.prepareCell(news: newsList[indexPath.row]) return cell } else if sectionType == .homeAuthor { let cell : HomeAuthorCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeAuthorCollectionViewCell", for: indexPath) as! HomeAuthorCollectionViewCell cell.prepareCell(news: newsList[indexPath.row]) return cell } else { let cell : HeadlineNewsCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "HeadlineNewsCollectionViewCell", for: indexPath) as! HeadlineNewsCollectionViewCell cell.prepareCell(news: newsList[indexPath.row]) return cell } } When I launch the application, I get crash with error: *** Assertion failure in -[UICollectionView _dequeueReusableViewOfKind:withIdentifier:forIndexPath:viewCategory:], UICollectionView.m:6502 *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'could not dequeue a view of kind: UICollectionElementKindCell with identifier HeadlineNewsCollectionViewCell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard' I tried to give a reuse identifier name from the storyboard editor's but there is no difference.
2
0
2.2k
Jul ’21
Installed XCode extensions won't show up in the Editor menu after update to Version 12.5.1 (12E507)
I use these extensions for XCode: AlignmentForXcode BlockComment Comment Wrapper Convert to Multi-Line Function nef Paste JSON as Code I recently upgrade my device to Big Sur therefore XCode to the latest version. There was no issue with extensions before the upgrade, but now only a few of them show in the Editor menu. All of the extensions are enabled on System Preferences -> Extensions -> Xcode Source Editor. Also, some of those extensions that missing from the Editor menu are shown in the Key Bindings menu: Things I tried : Remove then Reinstall XCode from AppStore Remove then Reinstall Extensions not shown in the Editor menu Install different extensions: Some of them are shown but some of them are not. I don't know what is the difference between them, I installed extensions highlighted on App Store.
1
1
1.6k
Jul ’21
How to Improve WKWebKit Loading Time?
Problem: If a page contains a large-sized video, loading time takes too long because WKWebView caches the whole video. I have a WKWebView that loads elements from a remote server with loadHTMLString(). The problem is; if the page contains a video (which is near all the times, the page contains a large-sized video) the loading takes forever. Application's network usage goes to the limits of my bandwidth, so probably WKWebKit downloads the whole video from the server before it appears. This causes the loading indicator to be shown for solid 10 seconds, or a blank background if the indicator is disabled. Is there a way to improve this? Is there a way to start the download process of the video when the user presses the play button or show other elements excluding the video while loading the video itself?
0
0
744
Jun ’21
Swift - How to edit outlet in nib while “viewWillDisappear” on ViewController?
I have a two-file project. DetailCollectionViewCell includes a WKWebView that loads specific video and text embedded from the server. My goal is when the user clicks the back button, the video should be stopped. I've tried reloading or setting WebView's URL to nil, but I get Fatal Error and nil value for Web View every time I try to effect detailWebView. . ├── _PageViewController.swift │ └── viewWillDisappear() ├── _DetailCollectionViewCell.swift (File Owner of the nib) └── └── WKWebView: detailWebView DetailCollectionViewCell.swift (Where I populate data for WebView.) @objc protocol DetailCollectionViewCellDelegate { func reload() @objc func scrollAuthorAllColumns() } class DetailCollectionViewCell: UICollectionViewCell { @IBOutlet weak var detailWeb: WKWebView! var delegate: DetailCollectionViewCell? override func awakeFromNib() { super.awakeFromNib() detailWeb.navigationDelegate = self detailWeb.uiDelegate = self; detailWeb.autoresizingMask = UIView.AutoresizingMask(rawValue: UIView.AutoresizingMask.flexibleWidth.rawValue | UIView.AutoresizingMask.flexibleHeight.rawValue) } var itemAuthor: Column? { didSet { if let column = itemAuthor { if(PageViewController.itemId != column.itemId) { let webViewHeight = 50 as CGFloat self.webViewHeight.constant = webViewHeight self.wKWebViewHeight.constant = webViewHeight self.detailWeb.frame.size.height = webViewHeight DispatchQueue.main.asyncAfter(deadline: .now() + 1) { if(PageViewController.webViewHg <= Int(webViewHeight)) { HUD.show(HUDContentType.progress) } } self.detailWeb.isHidden = true self.delegate?.reload() let HTMLString = "my HTML string" detailWeb.loadHTMLString(String(HTMLString), baseURL: URL.init(fileURLWithPath: Bundle.main.bundlePath)) } } } } } PageViewController.swift override func viewWillDisappear(_ animated: Bool) { DetailCollectionViewCell.detailWeb.reload() "<--------- Crashes here. detailWebView = nil" "Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value" } extension PageViewController: DetailCollectionViewCell { func reload() { DispatchQueue.main.async{ self.collectionView.collectionViewLayout.invalidateLayout() } } func scrollAuthorAllColumns() { collectionView.scrollToItem(at: IndexPath.init(row: 0, section: 1), at: .top, animated: true) } I have 3 files in total; PageViewController.swift, DetailCollectionViewCell.swift, DetailCollectionViewCell.xib. I register the nib DetailCollectionViewCell in viewDidLoad on PageViewController with collectionView.register(UINib(nibName: "DetailCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "DetailCollectionViewCell") and show it in CollectionView defined in PageViewController.swift I also do think this is an instance issue, but I don't know how to work around it. I'd pass data with the delegate if this is a View Cell -> View Controller case, but this is a View Controller -> View Cell case and I don't know how to do what I want.
2
0
1.1k
May ’21
Swift - How to Call and Show XIB/StoryBoard inside from XIB?
Hi! I got confused while I am trying to achieve showing a xib or storyboard view inside of a xib view. I have a table filled with ViewCell xibs and every one of them has buttons for playing podcasts. When the user clicks the "play button", I want to show a full-screen player view top of the screen, like an alert notification with a close button, play button, volume slider, etc. If I create and show the player view inside of the cell xib, it only shows up to the size of a cell. I want to show the player view full-screen. Thus, I created another xib file and put the play button, volume slider, etc. in that file. But I can't call or show the player view xib from the table cell xib. How can I achieve this? How do I reach another xib file inside of a xib file? I tried this : swift let podcastViewCell = (UINib(nibName: "PodcastViewCell", bundle: nil), forCellWithReuseIdentifier: "PodcastViewCell") But couldn't get any value from this for now. Also, do you suggest using a storyboard view for showing it in xib? If so, I could use storyboard view too but I still need help calling it.
16
0
4.6k
May ’21
Swift - AVPlayer - Stop player in another cell when a new player starts
I am working on a podcast application and achieved all the streaming-related parts of the application. The problem explained below, how can I achieve this? Current: The player view is hidden by default. When the user presses the "Play" button, the player view unhides and the player starts streaming. But it won't stop streaming if the user presses another "Play" button so both streams play simultaneously. Goal: When the user starts playing a new podcast by pressing another Play button, I want other players would stop playing and disappear. Extra: The whole podcast view awakes from the xib cell. So, the problem is, how can I manipulate another cell view's member when pressing a button in another cell view
24
0
7.7k
May ’21