Whenever I run this code, after I have purchased something and it shifts up after leaving and reopening the page it crashes with the error "Index out of range".
Code - https://developer.apple.com/forums/content/attachment/86665b01-4c50-47bd-a14d-ef95b58db511
Ideas? Thanks in advance!
Ps: I can provide full project if needed.
Post
Replies
Boosts
Views
Activity
Hi,
I have this code that I need to run in the exact line order, but I can't figure out how to do it.
Things I have tried:
DispatchQueue Aysnc
completion handler functions
Code:
let pickedCat = Int.random(in: 1...4)
//print("picked cat: \(pickedCat)")
if pickedCat == 1 {
getRandomJokes()
randomJoke.text = "Random Joke: \(self.DadJokes)"
//print("Random Joke: \(self.DadJokes)")
}else if pickedCat == 2 {
getAssistantJokes()
randomJoke.text = "Random Joke: \(self.AssistantJokes)"
//print("Random Joke: \(self.AssistantJokes)")
}else if pickedCat == 3 {
getKnockKnockJokes()
randomJoke.text = "Random Joke: \(self.KnockKnockJokes)"
//print("Random Joke: \(self.KnockKnockJokes)")
}else if pickedCat == 4 {
getRandomJokes()
randomJoke.text = "Random Joke: \(self.RandomJokes)"
//print("Random Joke: \(self.RandomJokes)")
}
if randomJoke.text == "Random Joke: " {
randomJoke.text = "Random Joke: Failed to connect to server"
}
Hi,
Whenever I try to set a button's background image using the code below, the image goes blank instead of it changing. Ideas?
@IBAction func showSaveCatDescript(_ sender: Any) {
if showingSaveCatDescript == false {
toggleShowSaveCatDescript.setImage(UIImage(named: "questionmark.circle.fill"), for: .normal)
saveCatDescript.isHidden = false
showingSaveCatDescript = true
}else if showingSaveCatDescript == true {
toggleShowSaveCatDescript.setImage(UIImage(named: "questionmark.circle"), for: .normal)
saveCatDescript.isHidden = true
showingSaveCatDescript = false
}
}
Hi, I have a table view and am trying to implement a second, here is the code for the second one. The problem is the second one won't show any data. Please note that they're identical code:
import UIKit
import GoogleMobileAds
class Home: UIViewController, GADBannerViewDelegate, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var bannerView: GADBannerView!
@IBOutlet weak var ShowAds: UILabel!
@IBOutlet weak var bannerViewHeight: NSLayoutConstraint!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var Welcome: UILabel!
var names = [
Utilities.mostRecent
]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
checkRecentCat()
Utilities.checkads(bannerView: bannerView, bannerViewHeight: bannerViewHeight)
if Utilities.openNum == 1 {
Welcome.text = "Welcome! Check out our app. In the categories section you will find all of our jokes!"
}
bannerView.rootViewController = self
bannerView.delegate = self
if Utilities.ShowAds == true {
ShowAds.text = "Show Ads: True"
}else if Utilities.ShowAds == false {
ShowAds.text = "Show Ads: False"
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
checkRecentCat()
if UserDefaults.standard.bool(forKey: "JokesRUs.RemoveAds") {
Utilities.ShowAds = false
bannerViewHeight.constant = 0
ShowAds.text = "Show Ads: False"
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("index path: \(indexPath.row)")
let row = indexPath.row
if row == 0 {
self.performSegue(withIdentifier: Utilities.mostRecentSegue!, sender: self)
}else if row == 1 {
self.performSegue(withIdentifier: Utilities.secondRecentSegue!, sender: self)
}else if row == 2 {
self.performSegue(withIdentifier: Utilities.thirdRecentSegue!, sender: self)
}
tableView.deselectRow(at: indexPath, animated: true)}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) - Int {
return names.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) - UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = names[indexPath.row]
return cell
}
func checkRecentCat() {
print("Most Recent Cat: \(Utilities.mostRecent ?? nil)")
print("Second Most Recent Cat: \(Utilities.secondRecent ?? nil)")
if Utilities.secondRecent == nil || Utilities.secondRecentSegue == nil || Utilities.secondRecent == "Please choose a category to show" || Utilities.secondRecentSegue == "Please choose a category to show" {
Utilities.setSecondRecent(id: "Please choose a category to show", segue: "categories")
}
if Utilities.thirdRecent == nil || Utilities.thirdRecentSegue == nil || Utilities.thirdRecent == "Please choose a category to show" || Utilities.thirdRecentSegue == "Please choose a category to show" {
Utilities.setThirdRecent(id: "Please choose a category to show", segue: "categories")
}
if Utilities.mostRecent == nil || Utilities.mostRecentSegue == nil || Utilities.mostRecent == "Please choose a category to show" || Utilities.mostRecentSegue == "Please choose a category to show" {
Utilities.setMostRecent(id: "Please choose a category to show", segue: "categories")
tableView.isHidden = true
}else {
names = [Utilities.mostRecent]
if Utilities.secondRecent == nil || Utilities.secondRecentSegue == nil || Utilities.secondRecent == "Please choose a category to show" {
}else {
names = [Utilities.mostRecent, Utilities.secondRecent]
if Utilities.thirdRecent == nil || Utilities.thirdRecentSegue == nil || Utilities.thirdRecent == "Please choose a category to show" {
}else {
names = [Utilities.mostRecent, Utilities.secondRecent, Utilities.thirdRecent]
}
}
}
}
Hi,
I am using Mac in Cloud, because I don't have a mac, and I am unable to load my app on to my phone, therefore I am trying to use testflight. The problem is my app is unpublished and the buttons for in-app aren't working. Any ideas.
Thanks in advance!
PS: The in-app purchase status is waiting for upload.
Hi, I have this code in a designated file called IAP Manager to handle all things related to in-app purchases.
import StoreKit
import Foundation
final class IAPManager: NSObject, SKProductsRequestDelegate, SKPaymentTransactionObserver {
static let shared = IAPManager()
private var products = [SKProduct]()
private var productBeingPurchased: SKProduct?
enum Product: String, CaseIterable {
case removeAds = "JokesRUs.RemoveAds"
}
public func fetchProducts() {
let request = SKProductsRequest(productIdentifiers: Set(Product.allCases.compactMap(({ $0.rawValue }))))
request.delegate = self
request.start()
}
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
products = response.products
}
func request(_ request: SKRequest, didFailWithError error: Error) {
guard request is SKProductsRequest else {
return
}
print("Product fetch request failed")
}
public func purchase(product: Product) {
guard SKPaymentQueue.canMakePayments() else {
return
}
guard let storeKitProduct = products.first(where: { $0.productIdentifier == product.rawValue }) else {
return
}
let paymentRequest = SKPayment(product: storeKitProduct)
SKPaymentQueue.default().add(self)
SKPaymentQueue.default().add(paymentRequest)
}
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
transactions.forEach({ transaction in
switch transaction.transactionState {
case .purchasing:
//No op
break
case .purchased:
handlePurchase(transaction.payment.productIdentifier)
break
case .failed:
break
case .restored:
break
case .deferred:
break
@unknown default:
break
}
})
}
private func handlePurchase(_ id: String) {
UserDefaults.standard.setValue(true, forKey: id)
print(id)
}
}
And then I have this code to call it:
IAPManager.shared.purchase(product: .removeAds)
The problem is I can't figure out how to get the price for the location from StoreKit.
Thanks in advance!
Hi,
I am making an app and I am using tab navigation controller and the navigation controller, and whenever I push into another view controller through a segue, if I go to a different tab, then back to that one it's still on the pushed to view controller. Ideas on how to fix this.
Thanks in advance!
Hi, this code is returning nil always. So frustrating!
let today = Date()
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents([.weekday], from: today)
let nineThirtyToday = Calendar.current.date(
bySettingHour: 90,
minute: 30,
second: 0,
of: today)
print(nineThirtyToday as Any)
if components.weekday == 4 {
if today = nineThirtyToday! {
if UDM.shared.widgetDefaults?.value(forKey: "currentRiddle") as! String == currentRiddleFinal {
currentRiddleFinal = "Waiting for update from server"
}
}else {
print("Not Nine Thirty")
}
}
UDM.shared.widgetDefaults?.setValue(currentRiddleFinal, forKey: "currentRiddle")
print("Current Riddle: \(currentRiddleFinal)")
}
Thanks in advance!
Hi,
I was downloading Xcode when it failed, now I can't download it, because I don't have enough space. I am running the newest non-beta version of Big Sur.
Thanks in advance
Hi,
I keep getting the error "Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols" on lines 99 and 100, here is the code:
import SwiftUI
import Intents
import UserNotifications
class Riddles {
static var text = String()
static var isWednesday = Bool()
static func largeWidget() {
Riddles.checkWeekday()
let userDefaults = UserDefaults(suiteName: "group.SetRiddle")
if Riddles.isWednesday == false {
if userDefaults?.value(forKey: "currentRiddle") != nil || userDefaults?.value(forKey: "previousRiddle") != nil {
Riddles.text = "\(UserDefaults(suiteName: "group.SetRiddle")?.value(forKey: "currentRiddle") as! String) \n\n\(UserDefaults(suiteName: "group.SetRiddle")?.value(forKey: "previousRiddle") as! String)"
}else{
Riddles.text = "Please open app to display riddle"
}
}else {
Riddles.text = "Please open app to display riddle"
}
}
static func mediumWidget() {
Riddles.checkWeekday()
let userDefaults = UserDefaults(suiteName: "group.SetRiddle")
if Riddles.isWednesday == true {
if userDefaults?.value(forKey: "currentRiddle") != nil {
Riddles.text = UserDefaults(suiteName: "group.SetRiddle")?.value(forKey: "currentRiddle") as! String
}else{
Riddles.text = "Please open app to display riddle"
}
}else {
Riddles.text = "Please open app to display riddle"
}
}
static func checkWeekday() {
let today = Date()
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents([.weekday], from: today)
if components.weekday == 4 {
Riddles.isWednesday = true
}else {
Riddles.isWednesday = false
}
}
}
struct Provider: IntentTimelineProvider {
func placeholder(in context: Context) -> SimpleEntry {
SimpleEntry(date: Date(), text: "", configuration: ConfigurationIntent())
}
func getSnapshot(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (SimpleEntry) -> ()) {
let entry = SimpleEntry(date: Date(), text: "", configuration: configuration)
completion(entry)
}
func getTimeline(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
var entries: [SimpleEntry] = []
// Generate a timeline consisting of five entries an hour apart, starting from the current date.
let currentDate = Date()
for hourOffset in 0 ..< 5 {
let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)!
let entry = SimpleEntry(date: entryDate, text: "", configuration: configuration)
entries.append(entry)
}
let timeline = Timeline(entries: entries, policy: .atEnd)
completion(timeline)
}
}
struct SimpleEntry: TimelineEntry {
let date: Date
let text: String
let configuration: ConfigurationIntent
}
struct RiddleWidgetEntryView : View {
var entry: Provider.Entry
@Environment(\.widgetFamily) var family: WidgetFamily
@ViewBuilder
var body: some View {
switch family {
case .systemMedium: Riddles.mediumWidget()
case .systemLarge: Riddles.largeWidget()
}
ZStack {
Text(Riddles.text)
.foregroundColor(.black)
.font(Font.system(size: 20))
}
}
}
@main
struct RiddleWidget: Widget {
let kind: String = "RiddleWidget"
var body: some WidgetConfiguration {
IntentConfiguration(kind: kind, intent: ConfigurationIntent.self, provider: Provider()) { entry in
RiddleWidgetEntryView(entry: entry)
}
.configurationDisplayName("My Widget")
.description("This is an example widget.")
.supportedFamilies([.systemMedium, .systemLarge])
}
}
struct RiddleWidget_Previews: PreviewProvider {
static var previews: some View {
RiddleWidgetEntryView(entry: SimpleEntry(date: Date(), text: "This Weeks Riddle: ", configuration: ConfigurationIntent()))
.previewContext(WidgetPreviewContext(family: .systemSmall))
}
}
Thanks in advance
Hi,
how can I check if someone has allowed local notifications?
Thanks in advance!
Hi,
I would like to be able to take two fields of a firestorm document and then set two UILabels to those fields. Here is my code:
import SafariServices
import WebKit
import Firebase
class TheRiddle: UIViewController {
@IBOutlet weak var leading_TheRiddle: NSLayoutConstraint!
@IBOutlet weak var trailing_TheRiddle: NSLayoutConstraint!
@IBOutlet weak var CurrentRiddle: UILabel!
@IBOutlet weak var PreviousRiddle: UILabel!
var menuOut = false
override func viewDidLoad() {
super.viewDidLoad()
let db = Firestore.firestore()
db.collection("TheRiddle").document("Riddles").getDocument { (document, error) in
//check for error
if error == nil {
//check if document exists
if document != nil {
}else {
if let currentRiddle = document!.get("CurrentRiddle") as? String {
self.CurrentRiddle.text = "This Weeks Riddle: " + currentRiddle
}
if let previousRiddle = document!.get("CurrentRiddle") as? String {
self.CurrentRiddle.text = "Previous Riddle: " + previousRiddle
}
}
}
}
}
@IBAction func RiddleAnswerForm(_ sender: Any) {
let vc = SFSafariViewController(url: URL(string: "https://forms.office.com/Pages/ResponsePage.aspx?id=ytAqTDte6UK-KD5v_kOm4Y843IzqmYtFlDtLrfRYsi1UMFpUMk1GN01GS05BVFlJUElONk4yR1hKUCQlQCN0PWcu")!)
present(vc, animated: true)
}
@IBAction func menuTappedTheRiddle(_ sender: Any) {
if menuOut == false {
leading_TheRiddle.constant = 150
trailing_TheRiddle.constant = -150
menuOut = true
}
else {
leading_TheRiddle.constant = 0
trailing_TheRiddle.constant = 0
menuOut = false
}
UIView.animate(withDuration: 0.2, delay: 0.0, options: .curveEaseIn, animations: {
self.view.layoutIfNeeded()
}) { (animationComplete) in
print("The animation is complete")
}
}
}
Thanks in advance!
Hi, I am trying to make it so that my notification opens up the “The Riddle” View controller, but I can’t figure out how. Here is a link: https://www.icloud.com/iclouddrive/0PDX_ZK3kyamqHjV8-hlDhZbw#Riddle_Wednesday
Thanks in advance!
Hi,
Something weird is going on with my code. I want it so when someone allows me to send notifications, if they go into my setting view controller to see that toggled on. Here is a link to my project: https://www.icloud.com/iclouddrive/0PDX_ZK3kyamqHjV8-hlDhZbw#Riddle_Wednesday
Thanks in advance!
Hi,
Is there a way I can use something like an res feed to update text weekly without using a paid server?
Thanks in advance!