I have a userDefault using Appstorage and would like to have a function access that value to use in a switch. What would be the best approach to accomplish this?
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I'm running into an issue where I'm trying to do two things
Uncheck an existing checkbox when another one is checked. Basically only allow for one state to be active.
When I have one boxed checked every box is showing checked when the pages appears as a sheet.
Here's a repro of what i'm working on.
struct Themes: View {
var body: some View {
List {
ForEach (themeData) { themedata in
ThemesView(themedata: themedata)
}
.padding()
}
}
}
struct ThemesView: View {
var themedata: themes
@State var themedCheck = UserDefaults.standard.bool(forKey: "ThemeChecked")
@State var themeColorUserSetting = UserDefaults.standard.string(forKey: "ThemeColor")
@State var themeColor = "card3"
var body: some View {
HStack(spacing: 16) {
Circle()
.fill(Color(themedata.color))
.frame(width: 25, height: 25, alignment: .center)
Text(themedata.name)
.font(.custom("ProximaNova-Regular", size: 18))
Text("\(self.themeColor)")
Spacer()
ZStack {
RoundedRectangle(cornerRadius: 7)
.stroke(style: StrokeStyle(lineWidth: 1.5))
.frame(width: 35, height: 35)
.foregroundColor(themedCheck ? Color("card2") : Color.gray.opacity(0.2))
RoundedRectangle(cornerRadius: 7)
.trim(from: 0, to: 1)
.fill(themedCheck ? Color("card2") : Color.gray.opacity(0.2))
.frame(width: 25, height: 25)
if themedCheck {
Image(systemName: "checkmark")
.foregroundColor(Color.white)
}
}
.onTapGesture{
if !self.themedCheck {
withAnimation(Animation.easeIn(duration: 0.5)) {
self.themedCheck.toggle()
UserDefaults.standard.set(self.themedCheck, forKey: "ThemeChecked")
UserDefaults.standard.set(self.themeColorUserSetting, forKey: "ThemeColor")
self.themeColor = themedata.color
}
} else {
withAnimation{
self.themedCheck.toggle()
UserDefaults.standard.set(self.themedCheck, forKey: "ThemeChecked")
self.themeColor = "card3"
}
}
}
}
}
}
struct themes: Identifiable {
var id = UUID()
var name: String
var color: String
}
let themeData = [
themes(name: "Default", color: "card3"),
themes(name: "Theme 1", color: "Theme1"),
themes(name: "Theme 2", color: "Theme2")
]
I know about .onDelete modifier, but say I want to remove an item from Coredata using onTapGesture is that possible?
.onDelete { indexSet in
let deleteItem = self.isFavorite[indexSet.first!]
self.managedObjectContext.delete(deleteItem)
do {
try self.managedObjectContext.save()
}catch {
print(error)
}
}
I tried doing
.onTapGesture { indexSet in
let deleteItem = self.isFavorite[indexSet.first!]
self.managedObjectContext.delete(deleteItem)
do {
try self.managedObjectContext.save()
}catch {
print(error)
}
}
But that didn't go well.
I found in the latest update of iOS and xCode that onTapGesture isn't consistently registering onTap. Here's a stripped down version of the code I'm using that reproduces this issue. In this case onTap for safari is not working.
I don't reproduce this with iOS13 or if I'm using onLongPress
Has anyone else experienced this in the latest update?
@State var runclubs: [RunClubsv2] = []
//Search filter
@State var showSearch = false
@State private var searchText: String = ""
@Binding var showRuns: Bool
@State var tap = false
@State var showActionSheet = false
//States for weeks
@State var hideSunday = false
@State var hideFavorites = false
//View
@State var clubInfo = false
@State private var urlString = ""
@State private var showSafari = false
var body: some View {
ZStack {
VStack {
List {
//TODO: Add section filtering.
HStack {
Text("Run Clubs")
.font(.title).bold()
Spacer()
}
Section(header:
HStack {
Text("Sunday")
.font(.subheadline)
.padding(.vertical, 5)
Image(systemName: hideSunday ? "chevron.up": "chevron.down")
.foregroundColor(Color("carolinablue"))
.rotation3DEffect(Angle(degrees: hideSunday ? 180 : 0), axis: (x: 0, y: 90, z: 0))
}
.animation(.easeInOut(duration: 0.2))
.onTapGesture {
self.hideSunday.toggle()
})
{
if hideSunday == false {
//display data
ForEach(runclubs.filter({
searchText.isEmpty ? true : $0.name.lowercased().contains(searchText.lowercased())
})) { item in
if item.category == "Sunday" {
ZStack {
HStack {
//MARK: Background color
Color(clubInfo ? "carolinablue" : "card3")
.frame(width: 30, height: 575)
.cornerRadius(3)
.frame(width: 6, height: 75, alignment: .leading)
.background(Color( colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)).opacity(0.08))
.cornerRadius(3)
.padding()
.frame(width: 3, height: 55)
.background(Color.black.opacity(0.1))
.cornerRadius(12)
.scaleEffect(clubInfo ? 0.8 : 1)
.animation(.interpolatingSpring(mass: 1.0,stiffness: 100, damping: 6.0))
//MARK: Runclub top section
VStack(alignment: .leading, spacing: 8.0) {
HStack {
ZStack(alignment: .leading) {
Text(item.name)
.font(.headline)
.animation(.easeOut(duration: 0.4))
.rotation3DEffect(Angle(degrees: clubInfo ? 90 : 0), axis: (x: 90, y: 0, z: 0))
Text(item.location)
.font(.headline)
.rotation3DEffect(Angle(degrees: clubInfo ? 0 : 90), axis: (x: 90, y: 0, z: 0))
.animation(.easeOut(duration: 0.4))
}
Spacer()
Image(systemName: clubInfo ? "chevron.up": "chevron.down")
.font(.system(size: 20, weight: .medium))
.foregroundColor(Color("carolinablue"))
.rotation3DEffect(Angle(degrees: clubInfo ? 180 : 0), axis: (x: 0, y: 90, z: 0))
.shadow(color: Color("carolinablue"), radius: 12, x: 0, y: 0)
.onTapGesture{
self.clubInfo.toggle()
}
}
//MARK: Runclub bottom section
HStack {
ZStack(alignment: .leading) {
HStack {
Image(systemName: "safari")
Text("Link for more Info")
.font(.subheadline)
.onTapGesture {
self.showSafari = true
self.urlString = item.link
print("urlString \(self.urlString)")
}
Spacer()
}
.animation(.easeOut(duration: 0.4))
.rotation3DEffect(Angle(degrees: clubInfo ? 0 : 90), axis: (x: 90, y: 0, z: 0))
// .allowsHitTesting(clubInfo ? true : false)
HStack {
Text(item.location)
.font(.subheadline)
.rotation3DEffect(Angle(degrees: clubInfo ? 90 : 0), axis: (x: 90, y: 0, z: 0))
Spacer()
//
}
}
.animation(.easeOut(duration: 0.4))
}
}
//testing long press here to prevent scrolling issues.
.onLongPressGesture {
self.showSafari = true
self.clubInfo = false
self.urlString = item.link
}
}
}
.sheet(isPresented: $showSafari) {
SafariView(urlString: self.$urlString)
}
.padding(.horizontal, 15)
.frame(height: 90)
.background(Color(clubInfo ? "background3" : "background2"))
.animation(.easeInOut(duration: 0.3))
.clipShape(RoundedRectangle(cornerRadius: 20, style: .continuous))
.shadow(color: Color("background2").opacity(0.8), radius: 10, x: 0, y: 10)
.padding(.vertical, 13)
}
}
}
}
}
}
.padding(.top, 15)
.onTapGesture {
self.hideKeyboard()
}
.navigationBarItems(trailing: EditButton())
}
//MARK: Call for run club data
.onAppear{
print("onappear making API call for data")
Api().getRunClub(url: "https://api.npoint.io/a5a1f2a53b3856ceed34") { (runclubs) in
self.runclubs = runclubs
print("We got the run run clubs")
}
}
.padding(.top, 65)
}
}
I'm trying to plot out map annotations from a JSON Response using MapKit. I've figured out some basic ways to plot out map points, but I"m not sure entirely what MapKit is expecting for map points. In my JSON response my struct is
// MARK: - Business
struct Business: Codable, Identifiable {
let id, alias, name: String
let coordinates: Center
}
struct Center: Codable {
let latitude, longitude: Double
}
Then my code looks like this, but I think I'm using CLLocationCoordinate2DMake incorrectly.
@State var yelpbusinessdataMap: WelcomeBusiness? = nil
var body: some View {
Map(coordinateRegion: $region,
interactionModes: MapInteractionModes.all,
showsUserLocation: true,
userTrackingMode: $userTrackingMode,
annotationItems: yelpbusinessdataMap?.businesses ?? []
)
{ places in
var new2DCoord = CLLocationCoordinate2DMake(places.coordinates.latitude, places.coordinates.longitude)
MapAnnotation(
coordinate:
new2DCoord,
anchorPoint: CGPoint(x: 0.5, y: 0.5)
){
Circle()
.stroke(Color.green)
.frame(width: 44, height: 44)
}
}
I tried using coordinate: places.coordinates,, but I get the following compiler error
Cannot convert value of type 'Center' to expected argument type 'CLLocationCoordinate2D'
I created a class and a function to make an API call and return some data. I get the data back in the console, but I'm not able to use the data and I think it's because I'm not completing the data correctly. The data being returned is surrounded by { } instead of [ ].
The function looks like this:
func getBusinessInfo(completion: @escaping ([Welcome]) -> ()) {
...
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
...
if let yelpbusinessinfo = data {
let decoder = JSONDecoder()
let yelpbusinessinfo = try? decoder.decode(Welcome.self, from: yelpbusinessinfo)
print(yelpbusinessinfo?.reviews[1].text)
completion(yelpbusinessinfo!)
}
At completion(yelpbusinessinfo!) I get the following error in the compiler and I'm assuming it has to do with how the data is being returned.
Cannot convert value of type 'Welcome' to expected argument type '[Welcome]'
Any help on what the proper format should be?
New SwiftUI files are no longer rendering preview in canvas. I'm getting the error
MessageSendingError: Connection interrupted: send previewInstances message to agent.	
Existing views still render so far, but the default hello world isn't rendering.
I've restarted Xcode, my mac, clean and rebuilt the project and no change. I've tried add .environment(\.colorScheme, .dark) to the preview and that made no difference as well.
What am I missing?
I have an app that is crashing only in iOS13. I don't see this issue on my iOS14 device or the simulator.
Here's the error I get in the console and I included the breakpoint error. The crash is happening on line 14.
Context in environment is not connected to a persistent store coordinator: <NSManagedObjectContext: 0x281050c40>
Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1bf7c5678)
struct BLAH: View {
//		Core data
		@Environment(\.managedObjectContext) var managedObjectContext
		@FetchRequest(fetchRequest: FavoriteItem.getAllFavorites()) var isFavorite:FetchedResults<FavoriteItem>
		var body: some View {
		...
		List {
			 ...
						if hideFavorites == false {
								ForEach(isFavorite.filter({ <CRASH HERE>
										searchText.isEmpty ? true : $0.name.lowercased().contains(searchText.lowercased())
								})) {isFavorite in
										FavoriteView(
												runclub: RunClubsv2.init(id: isFavorite.runclubid, name: isFavorite.name, location: isFavorite.location, date: isFavorite.date, category: isFavorite.category, dayofweek: isFavorite.dayofweek, link: isFavorite.link, hour: isFavorite.hour, minute: isFavorite.minute, favorite: false),
												name: isFavorite.name,
												date: isFavorite.date,
												location: isFavorite.location,
												link: isFavorite.link,
												category: isFavorite.category,
												dayofweek: isFavorite.dayofweek,
												hour: isFavorite.hour,
												minute: isFavorite.minute,
												runclubid: isFavorite.runclubid
										)
								}.onDelete { indexSet in
										let deleteItem = self.isFavorite[indexSet.first!]
										self.managedObjectContext.delete(deleteItem)
										do {
												try self.managedObjectContext.save()
										}catch {
												print(error)
										}
								}
						}
				}
		}
}
So I call FetchRequest to get the data.
@FetchRequest(fetchRequest: FavoriteItem.getAllFavorites()) var isFavorite:FetchedResults<FavoriteItem>
When I print out isFavorite I can see all the data in my coredata model, but I'm not sure how I can run a contain that data.
This is what I thought would work
if isFavorite.contains(foo.name) {
print("it's already there nerd")
}
I get the error Cannot convert value of type 'String' to expected argument type 'FetchedResults<FavoriteItem>.Element' (aka 'FavoriteItem')
Do I need to do a foreach and check each item?
Starting in Xcode 12 buttons are causing my code to not compile.
At the basic level it's failing which was not failing in Xcode 11.*.
import SwiftUI
struct Foo1: View {
var body: some View {
VStack {
Button(action: print("How about now?")) {
Text("test")
}
}
}
}
struct Foo1_Previews: PreviewProvider {
static var previews: some View {
Foo1()
}
}
I noticed that with iOS14 navigationlinks and button content show all content as blue. The weird thing is if I pull down slightly on the sheet the colors revert.
Here's a video of what I'm talking about.
https://www.icloud.com/iclouddrive/02Ywhk6SiZn4NhUU45cZ2MNPw#iOS14
I tried using .renderingMode(.original) but that hasn't helped.
I'm using Xcode 11.7 and my app is targeted for 13.1 and when changing the State of a property in quick succession the app is crashing to a black screen and then returns to the lock screen.
I'm not getting any crash report on the device and when I hook it up to Xcode I just get the following errors:
2020-09-15 06:42:28.586026-0400 [26842:7830878] XPC connection interrupted
2020-09-15 06:42:28.589083-0400 [26842:7831204] [ServicesDaemonManager] interruptionHandler is called. -[FontServicesDaemonManager connection]_block_invoke
I'm not really sure how to troubleshoot this.