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'
Post not yet marked as solved
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?
Post not yet marked as solved
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()
}
}
Post not yet marked as solved
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.
Post not yet marked as solved
The scenario is I have several events that happen every X day.
Event1 would be every Monday @ some time
Event2 would be every Friday @ some time
and so on
What's an ideal way to ensure I'm adding the event to the correct day without a start day? If the user picks to add Event2 on a Thursday how am I sure I get it added to following Friday.
I'm getting into a crash only with iOS14 and Xcode 14 simulator. I don't see this issue when I was on iOS13 or Xcode 13 simulator.
I'm using SafariServices to open a URL and the crash is happening at
SafariView(url: URL(string: self.urlString)!)
I felt fine forcing the unwrap because I know that self.urlString = self.dogood.link has a value from an Identifiable that I'm using. Am I looking at an iOS 14 bug possibly?
struct SafariView: UIViewControllerRepresentable {
typealias UIViewControllerType = SFSafariViewController
var url: URL?
func makeUIViewController(context: UIViewControllerRepresentableContext<SafariView>) -> SFSafariViewController {
return SFSafariViewController(url: url!)
}
func updateUIViewController(_ safariViewController: SFSafariViewController, context: UIViewControllerRepresentableContext<SafariView>) {
}
}
struct DoGoodListView: View {
@State private var showSafari = false
@State private var urlString = ""
var dogood: DoGood
var body: some View {
VStack(spacing: 8.0) {
HStack {
Text(dogood.name)
.font(.title).bold()
Spacer()
Image(dogood.logo)
.resizable()
.aspectRatio(contentMode: .fit)
.cornerRadius(15)
.frame(width: 50, height: 50)
}
Text(dogood.info)
Button(action: {
self.urlString = self.dogood.link
self.showSafari = true
print(self.urlString)
}) {
Text("Visit")
.font(.system(size: 18, weight: .medium))
.frame(width: 250, height: 50)
.background(Color("card3"))
.clipShape(RoundedRectangle(cornerRadius: 30, style: .continuous))
.shadow(color: Color("card3").opacity(0.1), radius: 1, x: 0, y: 1)
.shadow(color: Color("card3").opacity(0.2), radius: 10, x: 0, y: 10)
.padding()
}
.sheet(isPresented: $showSafari) {
SafariView(url: URL(string: self.urlString)!)
}
}
}
}
I'm wanting to present an alert message when a user doesn't have network connection.
I have a function that will make an API call for data and also checking if there is network connectivity to avoid a crash. I'm sort of stuck on the best approach from here.
func getRoutes(completion: @escaping ([Route]) -> ()) { //Post is data model
				let routeMonitor = NWPathMonitor()
				print("aMonitor is set")
				routeMonitor.pathUpdateHandler = { path in
						if path.status == .satisfied {
								print("We're connected! Let's grab route data")
								guard let url = URL(string: "<URL>") else { return
										print("the JSON data didn't match")
								}
								URLSession.shared.dataTask(with: url) { (data, _, _) in //_ means we're not going to use it now
										let routes = try? JSONDecoder().decode([Route].self, from: data!) //decoding the data
										//allow us to interact with the app while API call is happening
										DispatchQueue.main.async {
												if routes != nil	{
														completion(routes!)
//														print(routes!)
												} else {
														//TODO: Update error message
														print("we're trying to get route data - errorstate \(self.dataError), alert state \(self.showingAlert)")
												}
										}
								}
								.resume()
						} else {
								self.dataError = true
								print("No connection & data error set to \(self.dataError).")
						}
						print("Cell Data set to \(path.isExpensive)")
				}
				let routeQueue = DispatchQueue(label: "Route Monitor")
				routeMonitor.start(queue: routeQueue)
		}
}
Here's the call I make for onAppear to call the function
//MARK: API call to get race data
.onAppear{
Api().getRoutes{
(routes) in
self.routes = routes
print("Obserbed object: \(self.presentError.dataError)")
if self.presentError.dataError == true {
print("routeview error on getting data from api.getPosts \(self.presentError.dataError)")
return
}
}
}
I thought I could put an if statement after (routes) in, but I never get to that far when there is no network connecvitiy.
Post not yet marked as solved
My main project is fine and builds fine, but my tests portion of my project is giving the error below
Signing for "appTests" requires a development team. Select a development team in the Signing & Capabilities editor.
I've confirmed that I have a Team selected as well as a signing cert.
I'm new to SwiftUI and when I use the onChange modifier I get the following error.
Value of type 'some View' has no member 'onChange'
Here's the section of my code and if I remove line 9 - 26 my code will compile.
GeometryReader{reader in
VStack {
Image("race2")
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: UIScreen.main.bounds.width, height: reader.frame(in: .global).minY > 0 ? reader.frame(in: .global).minY + (UIScreen.main.bounds.height / 2.2) : UIScreen.main.bounds.height / 2.2)
.offset(y: reader.frame(in: .global).minY)
.onChange(of: reader.frame(in: .global).minY){value in
let offset = value + ( UIScreen.main.bounds.height / 2.2)
if offset < 80 {
if offset > 0 {
let opactity_value = (80 - opactity) / 80
self.opacity = Double(opactity_value)
return
}
self.opacity = 1
}
else {
self.opacity = 0
}
}
}
}