Post not yet marked as solved
Hello everybody,
I am trying to create a custom annotation for a map view. Everything works perfectly, except for the UIImage I am trying to show that does not appear.
I think I am not being able to show the MKAnnotationView I am trying to set.
In the mapView method I am not being able to perform that print statement. I can't figure out why.
import SwiftUI
import UIKit
import MapKit
class ObservationAnnotation: NSObject, MKAnnotation {
let coordinate: CLLocationCoordinate2D
let title: String?
let subtitle: String?
var image: UIImage?
init(coordinate: CLLocationCoordinate2D, species: String, image: UIImage, confidence: Double) {
self.coordinate = coordinate
self.title = species
self.subtitle = "Confidence: \(confidence)"
self.image = image
}
}
class ObservationAnnotationView: MKAnnotationView {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
guard
let observationAnnotation = self.annotation as? ObservationAnnotation else {
return
}
image = observationAnnotation.image
}
}
struct MyObservationsMap: UIViewRepresentable {
var observationList: [Observation]
func makeUIView(context: Context) -> MKMapView {
MKMapView.init(frame: .zero)
}
func updateUIView(_ uiView: MKMapView, context: Context) {
for observation in observationList {
let annotation = ObservationAnnotation(
coordinate: CLLocationCoordinate2D(latitude: observation.latitude, longitude: observation.longitude),
species: observation.speciesName!,
image: UIImage(data: observation.image!)!,
confidence: observation.confidence
)
uiView.addAnnotation(annotation)
}
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let reuseId = "observation"
let annotationView = ObservationAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
annotationView.canShowCallout = true
print("Here")
return annotationView
}
}
Thank you!
Hello everybody,
I am currently implementing the sharing capability of my application. I want to share an image in JPEG format with text.
The problem is that when I use image.jpegData(compressionQuality: 0.8) and I try to post it on Twitter the popup does not show up. This does not happens when converting to pngData. I find this odd and I don’t know if this has happened to any of you but I an error about dismissing the view.
Here is my UIActivityViewController:
import SwiftUI
struct ShareSheet: UIViewControllerRepresentable {
		
		var items: [Any]
		
		func makeUIViewController(context: UIViewControllerRepresentableContext<ShareSheet>) -> UIActivityViewController {
				
				let controller = UIActivityViewController(activityItems: items, applicationActivities: nil)
				return controller
		}
		
		func updateUIViewController(_ uiViewController: UIActivityViewController, context: UIViewControllerRepresentableContext<ShareSheet>) {}
}
I am creating my items array like this:
func getItemShareSheet() -> [Any] {
				
				let species = observation.speciesName
				let image = observation.image.pngData()
				let date = observation.date
				
				var finalText: String = ""
				
				if let location = observation.location {
						
						let latitude = String(format: "%.1f", Double(location.coordinate.latitude))
						let longitude = String(format: "%.1f", Double(location.coordinate.longitude))
						
						finalText = "New observation - \(date)\nSpecies: \(species)\nLatitude: \(latitude)\nLongitude: \(longitude)"
				}
				else {
						finalText = "New observation - \(date)\nSpecies: \(species)\n"
				}
				
				let items: [Any] = [image!, finalText]
				return items
		}
Has this happen to any of you?
Thank you!
Post not yet marked as solved
Hello everybody,
I have recently ran into a problem with my app the I am not being able to solve by myself.
I have implemented the new PHPicker. It is the best option to handle the new limited case where the app can only access photos approved by the user.
After having this completed I implemented the .requestAuthorization part of the application.
This is where my problem is.
At the moment, I have this code:
if #available(iOS 14, *) {
let accessLevel: PHAccessLevel = .readWrite
let status = PHPhotoLibrary.authorizationStatus(for: accessLevel)
switch status {
case .authorized:
self.imagePickerIsPresented.toggle()
case .limited:
print("Limited access - show picker.")
self.imagePickerIsPresented.toggle()
case .denied:
self.showPhotosAccessDeniedAlert.toggle()
case .notDetermined:
PHPhotoLibrary.requestAuthorization { newStatus in
switch newStatus {
case .authorized:
print("Full access.")
case .limited:
print("Limited access.")
break
case .denied:
break
default:
break
}
}
default:
break
}
}
First I check to see if the status is already determined. If it is not I call PHPhotoLibrary.requestAuthorization. Here things start to get really weird.
When I press "Select Photos" on my iPhone the picker to select the photos comes up and after I have selected the photos my code enters in the .authorized case and it prints "Full access".
However, after that when I try to open the picker it lands on the .limited case but the picker displays all the images in the camera roll and not only those I have selected.
Here is the code for my picker.
import SwiftUI
import PhotosUI
@available(iOS 14, *)
struct ImagePicker: UIViewControllerRepresentable {
@Binding var imageToImport: UIImage
@Binding var isPresented: Bool
@Binding var imageWasImported: Bool
func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> some UIViewController {
var configuration = PHPickerConfiguration()
configuration.filter = .images
configuration.selectionLimit = 1
let imagePicker = PHPickerViewController(configuration: configuration)
imagePicker.delegate = context.coordinator
return imagePicker
}
func updateUIViewController(_ uiViewController: ImagePicker.UIViewControllerType, context: UIViewControllerRepresentableContext<ImagePicker>) {}
func makeCoordinator() -> ImagePicker.Coordinator {
return Coordinator(parent: self)
}
class Coordinator: NSObject, PHPickerViewControllerDelegate {
var parent: ImagePicker
init(parent: ImagePicker) {
self.parent = parent
}
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
picker.dismiss(animated: true)
if results.count != 1 {
return
}
if let image = results.first {
print("Aqui")
if image.itemProvider.canLoadObject(ofClass: UIImage.self) {
image.itemProvider.loadObject(ofClass: UIImage.self) { image, error in
if let image = image {
print("Importou imagem")
self.parent.imageToImport = image as! UIImage
self.parent.imageWasImported.toggle()
}
}
}
}
self.parent.isPresented.toggle()
}
}
}
I am really struggling and all help is appreciated. Thanks a lot!
Hello,
In my application I am going to create a settings screen that will allow the user to change a couple of aspects in terms of how the core feature of the app works.
I have been wondering what might be the best way to save the user settings. I have considered global variables, binding variables and user defaults.
When it comes to global variables I don't think I have ever used them, with the exception of debugging. I kinda consider it a bad practice and I don't think all the screens of my app should have the ability to see and change this values.
Then, there is the possibility of using binding variables. I think this may be like trying to kill a fly with a war tank. I think it is too much and adds a lot of complexity to something that should be pretty straight-forward.
Finally, user defaults, to me, seems the best way to go. I can change it and keep persistency and it can be accessed easily.
What do you think is the best way to go?
Thank you for your help.
Post not yet marked as solved
Hello everybody,
I used Google Cloud Platform to create a Machine learning model to perform computer vision. I downloaded the CoreML model from the cloud platform website and followed the instructions in the Google Tutorial for iOS model deployment.
This is my code currently.
class Classification {
private lazy var classificationRequest: VNCoreMLRequest = {
do {
let model = try VNCoreMLModel(for: AutoML().model)
let request = VNCoreMLRequest(model: model, completionHandler: { [weak self] request, error in
if let classifications = request.results as? [VNClassificationObservation] {
print(classifications.first ?? "No classification!")
}
})
request.imageCropAndScaleOption = .scaleFit
return request
}
catch {
fatalError("Error! Can't use Model.")
}
}()
func classifyImage(receivedImage: UIImage) {
let orientation = CGImagePropertyOrientation(rawValue: UInt32(receivedImage.imageOrientation.rawValue))
if let image = CIImage(image: receivedImage) {
DispatchQueue.global(qos: .userInitiated).async {
let handler = VNImageRequestHandler(ciImage: image, orientation: orientation!)
do {
try handler.perform([self.classificationRequest])
}
catch {
fatalError("Error classifying image!")
}
}
}
}
My code executes and I receive this:
<VNClassificationObservation: 0x600002091d40> A7DBD70C-541C-4112-84A4-C6B4ED2EB7E2 requestRevision=1 confidence=0.332127 "CICAgICAwPmveRIJQWdsYWlzX2lv"
I receive a confidence value but I don't receive a label string.
Is there any step I am not taking?
With the model there is also a dict.txt file. Is there anything I have to do with that and that I am not doing?
Thank you!
Post not yet marked as solved
Hello everybody,
I am building a Map and I am using a map view that I want to be always present in the interface. However, the user can share to show its location or not.
The Map view requires a region. But I want to show an empty map view with just the grid on with a message.
Do you know if it is possible to achieve that? Thank you!
let span = MKCoordinateSpan(latitudeDelta: CLLOcationDegrees, longitudeDelta: CLLOcationDegrees)
let region = MKCoordinateRegion(center: observationCoordinates, span: span)
				
let annotation =	MKPointAnnotation()
annotation.coordinate = observationCoordinates
				
uiView.setRegion(region, animated: true)
uiView.addAnnotation(annotation)
Post not yet marked as solved
Hello everyone,
I want to use a map view to display an annotation but when I place it on the view it always stays in at the center of the map view.
I want to give it some offset so that it goes a little bit upwards.
This is the code I have so far. Could you please help me?
let span = MKCoordinateSpan(latitudeDelta: CLLOcationDegrees, longitudeDelta: CLLOcationDegrees)
let region = MKCoordinateRegion(center: observationCoordinates, span: span)
let annotation = MKPointAnnotation()
annotation.coordinate = observationCoordinates
uiView.setRegion(region, animated: true)
uiView.addAnnotation(annotation)
Thank you for your help.
Post not yet marked as solved
Hello everybody,I have an animation to create ballons floating from the bottom to the top of the screen. Despite producing the behaviour I want, at some point, when the ballons are floating upwards the objectView I am using one ballon gets printed at the top left corner of the screen and does not move or disappear.Has this ever happend to any of you?func presentVictoryView(word: String) {
blackView.isHidden = false
for _ in 0 ... 30 {
let objectView = UIView()
objectView.translatesAutoresizingMaskIntoConstraints = false
objectView.frame = CGRect(x: 0, y: 0, width: 20, height: 100)
objectView.backgroundColor = .clear
//objectView.alpha = CGFloat(0.9)
objectView.isHidden = false
let ballon = UILabel()
ballon.translatesAutoresizingMaskIntoConstraints = false
ballon.frame = CGRect(x: 0, y: 0, width: 20, height: 100)
ballon.backgroundColor = .clear
//ballon.alpha = CGFloat(0.9)
ballon.text = ""
ballon.font = UIFont.systemFont(ofSize: 60)
objectView.addSubview(ballon)
NSLayoutConstraint.activate([
ballon.centerXAnchor.constraint(equalTo: objectView.centerXAnchor),
ballon.centerYAnchor.constraint(equalTo: objectView.centerYAnchor)
])
blackView.addSubview(objectView)
let randomXOffset = Int.random(in: -120 ..< 200)
let path = UIBezierPath()
path.move(to: CGPoint(x: 160 + randomXOffset, y: 1000))
path.addCurve(to: CGPoint(x: 100 + randomXOffset, y: -300), controlPoint1: CGPoint(x: 300 - randomXOffset, y: 600), controlPoint2: CGPoint(x: 70 + randomXOffset, y: 300))
let animation = CAKeyframeAnimation(keyPath: "position")
animation.path = path.cgPath
animation.repeatCount = 1
animation.duration = Double(arc4random_uniform(40) + 30) / 10
//animation.timeOffset = Double(arc4random_uniform(50))
objectView.layer.add(animation, forKey: "animate position along path")
}
newGame()
}I have tried a lot of things... I don't know what I am doing wrong...Thank you!
Post not yet marked as solved
Hello,After reading the terms and conditions for the Challange I have a doubt..."Your Swift playground should not rely on a network connection and any resources used in your Swift playground should be included locally in your .zip file."My Playground has a Resources folder where I have all my resources. Does this requirement I quoted above means that we need to send the resources in a separate folder outside the playground?Thank you.
Post not yet marked as solved
Hello everybody!This may seem like a strange question but I would really like to use my Memoji created with iPhone 11 on my playground submission.Is that possible? Or may I risk being desqualified because of it?Thanks!
Hello everyone,I am working on a Playground and I can change the font type of my label. I have tried doing it in several different ways and I just can't do it.var clueLabel = UILabel()
clueLabel.font = UIFont(name: "MarkerFelt-Wide", size: 45)
clueLabel.font = UIFont.systemFont(ofSize: 45, weight: .bold)
clueLabel.textColor = UIColor.black
clueLabel.textAlignment = .center
view.addSubview(clueLabel)What am I doing wrong? I want to use the font Marker Felt.Thank you
Post not yet marked as solved
Hello everybody,I am having trouble in updating the text of a label. This only happens when I am about to call another function which is very strange.Here is my code:func updateWordLabelAndCheckVictory(letter: String, indexArray: [Int]) {
if let currentLabel = wordLabel.text {
var wordArray = Array(currentLabel)
for i in indexArray {
wordArray[i] = Character(letter)
}
wordLabel.text = String(wordArray)
if (game.checkVictory(label: wordLabel.text!)) {
currentGame += 1
presentVictoryView()
}
}
}I update the label in line 11. When the condition in line 13 is met the presentVictoryView method (line 15) executes before the label is updated... I don't really know what I am doing wrong. If I comment line 15 and don't call the presentVictoryView method the label is updated as usual...Could you please help me?Thank you.
Hello everybody,I am using a button trigger in Playgrounds to pass the button title to a function in another class.@objc func letterButtonPressed(_ sender: UIButton) {
sender.isHidden = true
hiddenButtons.append(sender)
letter = sender.currentTitle?.uppercased()
if letter != nil {
game.checkLetterInWord(letter: letter!)
}
}In this function above I check if the letter is nil first, so I don't undertstand why the function finds nil...public func checkLetterInWord(letter: String!) -> Bool {
print(letter!)
let wordCharacters = Array(word)
print(wordCharacters)
return true
}What am I doing wrong? Thank you for you help!
Post not yet marked as solved
Hello everybody,I am trying to start my Playgound in Xcode but I am finding it hard to work with. Everything I have done so far has been in normal Xcode. I create a new project and then everything is pretty straight-forward.But now I am trying to create a playground. I don't have code completion and I can't work this multiple files. Is there anything that I am doing wrong?Thank you. 🙂
Post not yet marked as solved
Hello everybody,I am trying to start my Playgound in Xcode but I am finding it hard to work with. Everything I have done so far has been in normal Xcode. I create a new project and then everything is pretty straight-forward.But now I am trying to create a playground. I don't have code completion and I can't work this multiple files. Is there anything that I am doing wrong?Thank you. 🙂