Post not yet marked as solved
Hi! I am trying to make a maze game, and right now I am simply working on generating the maze. I have code that randomizes the contents of an array called "right". This array has enough members to fill what the maze size is, but when I run my code, the views don't update, the ForEach function seems to make it so it cannot read data from my DataBase. Please help me?
import SwiftUI
struct ContentView: View {
@StateObject var data: DataBase
@StateObject var trafficControl: TrafficControl
var body: some View {
ZStack{
Group{
LazyVStack{
ForEach(1...data.size, id: \.self) { index in
LazyHStack {
ForEach(1...data.size, id: \.self) { box in
Rectangle().fill(Color.gray).frame(width: 90, height: 90, alignment: .center).scaledToFill().padding(-4)
}
}
}
}
LazyVStack{
ForEach(1...(data.size), id: \.self) { index in
LazyHStack {
ForEach(1...(data.size + 1), id: \.self) { box in
if data.**** == 1 {
Rectangle().fill(Color.gray).frame(width: 6, height: 90, alignment: .center).scaledToFill().padding(.trailing, 38).padding(.leading, 38).padding(.top, -4).padding(.bottom, -4)
}
else {
Rectangle().fill(Color.black).frame(width: 6, height: 90, alignment: .center).scaledToFill().padding(.trailing, 38).padding(.leading, 38).padding(.top, -4).padding(.bottom, -4)
}
}
}
}
}
LazyHStack{
ForEach(1...data.size, id: \.self) { index in
LazyVStack {
ForEach(1...(data.size + 1), id: \.self) { box in
Rectangle().fill(
Color.black).frame(width: 90, height: 6, alignment: .center).scaledToFill().padding(.top, 38).padding(.bottom, 38).padding(.trailing, -4).padding(.leading, -4)
}
}
}
}
Rectangle().fill(Color.white).frame(width: 60, height: 60, alignment: .center).scaledToFill()
}.offset(x: CGFloat(data.ex), y: CGFloat(data.why)).onAppear(){
print("\(data.size/2 + 1)")
}
Circle().fill(Color.black).frame(width: 20, height: 20, alignment: .center).scaledToFill()
}.gesture(DragGesture(minimumDistance: 40)
.onEnded { endedGesture in
if (endedGesture.location.x - endedGesture.startLocation.x) > 0 {
if (endedGesture.location.y - endedGesture.startLocation.y) > (endedGesture.location.x - endedGesture.startLocation.x) {
data.why -= 90
}
else if (endedGesture.startLocation.y - endedGesture.location.y) > (endedGesture.location.x - endedGesture.startLocation.x) {
data.why += 90
}
else {
data.ex -= 90
}
}
else if (endedGesture.startLocation.x - endedGesture.location.x) > 0 {
if (endedGesture.location.y - endedGesture.startLocation.y) > (endedGesture.startLocation.x - endedGesture.location.x) {
data.why -= 90
}
else if (endedGesture.startLocation.y - endedGesture.location.y) > (endedGesture.startLocation.x - endedGesture.location.x) {
data.why += 90
}
else {
data.ex += 90
}
}
else if (endedGesture.startLocation.y - endedGesture.location.y) > (endedGesture.location.y - endedGesture.startLocation.y) {
data.why += 90
}
else {
data.why -= 90
}
data.corx = data.ex/90
data.cory = data.why/90
}
)}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(data: DataBase(), trafficControl: TrafficControl())
}
}
Post not yet marked as solved
Hi,
I am developing an app which has a calendar integrated. This calendar comes from a package called CalendarKit (https://github.com/richardtop/CalendarKit ).
With this calendar you can access to all the events of you mobile integrated calendar and create new ones, modify them, delete, etc. All the events on you mobile calendar are going to be represented here and the same in the other way, everything that you create here will be represented on you mobile calendar.
So the main question is. How can i access to the 'Delete Event' action inside the 'Event Details' view?
I know that i can delete an event programmatically, but i need to "modify" the behavior when clicking on the item 'Delete Event'.
Is there any possible way to access to this item inside event details and when clicking on it do a custom action?.
For example, when clicking i want to:
print a text in the console,
show an alert,
get the EventID of the event deleted,
etc.
Can somebody help me with this??
Thanks a lot in advance.
I'm trying to format numbers in a UITextField consists of math equation String: "number + number".
At the moment I can type just a single number, then convert it to Double -> format with NSNumberFormatter -> convert back to String -> assign to textField.text: https://i.stack.imgur.com/4qQza.gif
The code:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
formatter.locale = .current
formatter.roundingMode = .down
let numberString = textField.text ?? ""
guard let range = Range(range, in: numberString) else { return false }
let updatedString = numberString.replacingCharacters(in: range, with: string)
let correctDecimalString = updatedString.replacingOccurrences(of: formatter.decimalSeparator, with: ".")
let completeString = correctDecimalString.replacingOccurrences(of: formatter.groupingSeparator, with: "")
guard let value = Double(completeString) else { return false }
let formattedNumber = formatter.string(for: value)
textField.text = formattedNumber
return string == formatter.decimalSeparator
}
Now I want to add a calculation functionality and display a simple math equation in a textField as "number + number", but each number should be formatted as shown on above screenshot. Example (but without formatting): https://i.stack.imgur.com/W7Jet.gif
I can't properly implement that. The logic for me was: track the String each time new char inserts -> if it has math sign extract numbers -> convert them to Double -> format with NSNumberFormatter -> convert back to String -> construct a new String "number + number".
The code I tried:
if let firstString = completeString.split(separator: "+").first, let secondString = completeString.split(separator: "+").last {
guard let firstValue = Double(firstString) else { return false }
guard let secondValue = Double(secondString) else { return false }
let firstFormattedNumber = formatter.string(for: firstValue)
let secondFormattedNumber = formatter.string(for: secondValue)
textField.text = "\(firstFormattedNumber ?? "") + \(secondFormattedNumber ?? "")"
// another try
if completeString.contains("+") {
let stringArray = completeString.components(separatedBy: "+")
for character in stringArray {
print(character)
guard let value = Double(character) else { return false }
guard let formattedNumber = formatter.string(for: value) else { return false }
textField.text = "\(formattedNumber) + "
}
}
But it's not working properly. I tried to search but didn't find any similar questions.
Test project on GitHub
How can I format the numbers from such a string?
Post not yet marked as solved
Code to reproduce:
let inputString = "url(https://example.com)"
let regex = Regex {
"url("
Capture {
.url()
}
")"
}
guard let (_, url) = inputString.firstMatch(of: regex)?.output else {
fatalError()
}
print(url)
Regex matches if we change "url(" to "(":
let regex = Regex {
"("
Capture {
.url()
}
")"
}
However, the output is
Is this a bug?
Post not yet marked as solved
I'm currently trying to save a selected image in core data as a type data, but I'm getting an error in the persistence file marked with a comment. I've included my code and any questions I will gladly answer. Thanks for any help!
Content View:
import SwiftUI
import PhotosUI
struct ContentView: View {
@ObservedObject var persistence = PersistenceController.shared
@State var selectedItems: [PhotosPickerItem] = []
@State var data: Data?
var body: some View {
NavigationView{
VStack{
Spacer()
VStack{
Spacer()
if let data = data, let uiimage = UIImage(data: data) {
Image(uiImage: uiimage)
.resizable()
.scaledToFit()
.frame(width: 250, height: 500)
}
Spacer()
}
Spacer()
PhotosPicker(selection: $selectedItems, maxSelectionCount: 1, matching: .images){
Text("Pick Photo")
}
.onChange(of: selectedItems){ newValue in
guard let item = selectedItems.first else{
return
}
item.loadTransferable(type: Data.self){ result in
switch result {
case .success(let data):
if let data = data{
self.data = data
} else {
print("Data is nil")
}
case .failure(let failure):
fatalError("\(failure)")
}
}
}
Spacer()
}
.navigationBarItems(trailing: addButton)
}
}
var addButton: some View {
Button(action: {
guard let item = selectedItems.first else{
return
}
item.loadTransferable(type: Data.self){ result in
switch result {
case .success(let data):
if let data = data{
persistence.addObject(image: data)
} else {
print("Data is nil")
}
case .failure(let failure):
fatalError("\(failure)")
}
}
}){
Text("Add Image").bold()
}
}
}
Persistence:
import Foundation
import CoreData
class PersistenceController: ObservableObject {
static let shared = PersistenceController()
let container: NSPersistentContainer
init(inMemory: Bool = false) {
container = NSPersistentContainer(name: "ReciPlanner")
if inMemory {
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
}
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
container.viewContext.automaticallyMergesChangesFromParent = true
}
func addObject(image: Data){
let context = container.viewContext
let object = Object(context: context) //Error: Thread 7: "An NSManagedObject of class 'Object' must have a valid NSEntityDescription."
object.item = image
}
func contextSave() {
let context = container.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
print("**** ERROR: Unable to save context \(error)")
}
}
}
}
Data Model:
Post not yet marked as solved
Below is a quick snippet of where I record audio. I would like to get a sampling of the background audio so that later I can filter out background noise. I figure 10 to 15 seconds should be a good amount of time.
Although I am assuming that it can change depending on the iOS device, the format returned from .inputFormat is :
<AVAudioFormat 0x600003e8d9a0: 1 ch, 48000 Hz, Float32>
Based on the format info, is it possible to make bufferSize for .installTap be just the write size for whatever time I wish to record for?
I realize I can create a timer for 10 seconds, stop recording, paster the files I have together, etc. etc. But if I can avoid all that extra coding it would be nice.
let node = audioEngine.inputNode
let recordingFormat = node.inputFormat(forBus: 0)
makeFile(format: recordingFormat)
node.installTap(onBus: 0, bufferSize: 8192, format: recordingFormat, block: {
[self]
(buffer, _) in
audioMetering(buffer: buffer)
print ("\(self.averagePowerForChannel0) \(self.averagePowerForChannel1)")
if self.averagePowerForChannel0 < -50 && self.averagePowerForChannel1 < -50 {
...
} else {
...
}
do {
... write audio file
} catch {return};})
audioEngine.prepare()
do {
try audioEngine.start()
} catch let error {
print ("oh catch \(error)")
}
Hello! I'm working with the UIHostingConfiguration and would like to set a Toolbar for a TextField which I placed in the content. I've tried to set ToolbarRole and Toolbar Visibility. Unfortunately, it doesn't work. Here's my example code:
Cell:
cell.configurationUpdateHandler = { (cell, state) in
cell.contentConfiguration = UIHostingConfiguration {
RowView(item: item)
}
}
View:
@ObservedObject var item: Movie
var body: some View {
TextField("Title", text: $item.title)
.toolbar(content: {
ToolbarItem(placement: .keyboard) {
Button("Confirm", action: {})
}
})
.toolbar(.visible, in: .automatic)
}
}
Post not yet marked as solved
Hi all,
I have a swift script that I've been running from the command line (macOS 12.4, Xcode 13.4.1) for a while with no issues.
I recently downloaded Xcode 14 beta 3 and the script no longer runs. It now fails with a "JIT session error: Symbols not found" error.
I can cut the script down to a very simple example
#!/usr/bin/swift
import Foundation
var url: URL = URL(fileURLWithPath: "/tmp")
I need to import Foundation to get access to the URL type for my script. Xcode 13.4.1 doesn't seem to need to do anything clever
% swift commandline-fail.swift
JIT session error: Symbols not found: [ _$s10Foundation3URLV15fileURLWithPathACSSh_tcfC, _$s10Foundation3URLVMa ]
Failed to materialize symbols: { (main, { __swift_FORCE_LOAD_$_swiftCoreFoundation_$_main, __swift_FORCE_LOAD_$_swiftDispatch_$_main, _$s4main3url10Foundation3URLVvp, __swift_FORCE_LOAD_$_swiftObjectiveC_$_main, __swift_FORCE_LOAD_$_swiftDarwin_$_main, _main, __swift_FORCE_LOAD_$_swiftXPC_$_main, __swift_FORCE_LOAD_$_swiftIOKit_$_main, ___swift_project_value_buffer, ___swift_allocate_value_buffer }) }
The failing swift version is
% swift --version
swift-driver version: 1.60 Apple Swift version 5.7 (swiftlang-5.7.0.120.1 clang-1400.0.28.1)
Target: x86_64-apple-macosx12.0
This script runs fine using
% swift --version
swift-driver version: 1.45.2 Apple Swift version 5.6.1 (swiftlang-5.6.0.323.66 clang-1316.0.20.12)
Target: x86_64-apple-macosx12.0
Does anyone have any ideas how I can solve this issue? It looks like the JIT needs access to the Foundation library but I have no idea how to do this.
Cheers!
Post not yet marked as solved
I am trying to write a Swift standalone library to monitor a UserDefaults value and callback a function in Python. To do so, I need an event loop in the Swift code that allows the Observer code to run and, when needed, call the callback function.
I am monitoring the default via a KVO Observer class, which inherits a NSObject with UserDefaults.standard.addObserver in its init and implements observeValue as callback.
To keep the loop running, up to now I called RunLoop.current.run() in the end of the Swift library invoked function. As you can imagine, this works well when the library is called from a main thread, which can provide inputs to the RunLoop.
On the other hand, this fails (the library returns immediately) when the function is invoked from a secondary thread without e.g. the stdin attached.
I am looking for an alternative to RunLoop.current.run() that:
runs indefinitely
can run in a secondary thread with no inputs
does not block callbacks to observeValue
I tried the most obvious choices like an infinite while or DispatchQueue but so far I was not able to achieve what I need.
Further details about the issue can be found in a related StackOverflow question here: https://stackoverflow.com/questions/72982210/swift-and-python-get-a-runloop-that-can-run-in-threading
Thanks in advance for your help.
Post not yet marked as solved
Hi Team,
We are trying to connect with our .pem file to apple, for testing pushnotification and here our UseCase
Send - Connection
Send -> Block
a few minutes later
Send -> Connection
Send -> Block
where
Block = connection refused, so it failed to even "connect" to apple
We also notice that the DNS resolved to many different IP addresses. Some work, some block
some IP addresses send us reset packets which means we get connection refused and some complete the TCP handshake and work.
When is the old SSL push notification supported up to before we have to swap to HTTP2?
we are trying to work out IF this is still supported?
any help would be appreciated
Thanks in advance.
Post not yet marked as solved
Swift Package Manager synthesises a module accessor for bundle resources (as described in WWDC 2020 Session 10169 Swift packages: Resources and localisation and SE-0271 > Runtime Access to Resources Bundle.
This is great, but I'd like to supply a different implementation of module. When I try to extend Bundle with my own module accessor the compiler complains that there are two module implementations. Is it possible to disable the SPM resource_bundle_accessor synthesis behaviour?
The professor codes like this in the lecture
var number: Int {
return 3 }
what's different about this?
var number: Int = 3
Currently I am placing a UITableView inside my UIViewController, with multiple other items. I am not using a UITableViewController.
However I am unable to register the identifier "masterlist", or should I say I am not sure where I can register it. I am not using storyboard, and if I am still to register it in my UIViewController's viewDidLoad, I am unable to figure out the proper syntax.
Is this something I can do?
class BeginNewCustomer: UIViewController {
let myList = createTblView()
override func viewDidLoad() {
super.viewDidLoad()
myList.delegate = self
myList.dataSource = self
}
func createTblView() -> UITableView {
let myTable = MyTableView(frame: CGRect(x: 0, y: 0, width: 0, height: 0 ))
myTable.backgroundColor = .white
return myTable
}
extension BeginNewInv: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dbClass.invsList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
// let cell = tableView.dequeueReusableCell(withIdentifier: "masterlist", for: indexPath)
var config = cell.defaultContentConfiguration()
.... fill the configuration
cell.contentConfiguration = config
return cell
}
}
Am trying to port away from .textLabel.text, as per Apple but I can't seem to find the way to get the text I set.
I now set my cells this way:
let cell = UITableViewCell()
var config = cell.defaultContentConfiguration()
config.text = dbClass.nameList[indexPath.row].clientName
config.textProperties.color = .black
config.textProperties.alignment = .center
cell.contentConfiguration = config
But when I try to get the text of a selected cell (once the user hits the OK button) I can't seem to reverse engineer how to get the text.
let cell = myClientList.cellForRow(at: myInvsList.indexPathForSelectedRow!)
let config = cell?.contentConfiguration
dbClass.curMasterinvList = ?????? (can't find what property to read here
I even tried
let config = cell?.defaultContentConfiguration()
Hoping that the text would be in there, but the text there is blank, so am assuming that's just the standard config before I've changed it.
I have Googled as much as possible, but can't seem to find this very simple need.
Post not yet marked as solved
I am working on a test app utilizing UISplitViewController. I search for ContainerView and drag it onto the Detail View. Then I search for an ImageView and drag it onto the Detail View. The ContainerView disappears and is replaced by the ImageView. I've deleted and recreated several times, and have also rebooted and it doesn't change how it works.
Have you experienced this or is there a fix?
I am using Xcode 13.4, and Monterey 12.4.
Post not yet marked as solved
I have an IOS application who uses coredata
As I want to develop and App extension which needs to share coredata with my app(Yes, I made a group App), I thought a good solution would be to create a framework with the, coredata model.
I did it, but after that the coredata of the main app is no longer necessary.
and I think I made a mistake when removing the file xcdatamodel from my app.
when I refer to an entity in the main application, it doesn't use the entity of the framework.
when I right click on an entity instance in my main application, I see a file which is: entity+CoreDataClass and of course I don't find it in the finder.
Did I made a mistake by simply remove the xcdatamodel from my App?
Do I have something to clean?
Post not yet marked as solved
Hi there,
The problem is that when I just drag and change the position of my label in xib, it does not effect properly in my app.
@IBOutlet weak var Example: UILabel! is connected to the label in xib file.
In total there are 3 labels, so I want to see them normal, but now it looks like the first label is inside the second label. The second and third label has huge spacing, and they are in very center. The first label is on very left side.
Appreciate your ideas.
Post not yet marked as solved
My app used to rely on standard iOS Numpad Keyboard as a textField.inputView. The textField could group typed numbers (1000 -> 1 000, 50067 -> 50 067 etc) and limit the amount of numbers after the decimal point as 2 max: https://i.stack.imgur.com/69LVr.gif (GIF)
I've created a custom numpad keyboard view and implement its logic with UITextInput protocol according to that guide on StackOverflow.
I can't understand of how to deal with the code I used for grouping and limit numbers with standard iOS Numpad. Because it doesn't work properly after I type numbers from my new custom Numpad (only 2 numbers): https://i.stack.imgur.com/f3u3n.gif (GIF)
The code I use for grouping and limit numbers after decimal point in a textField:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.groupingSeparator = " "
formatter.maximumFractionDigits = 2
let textString = textField.text ?? ""
guard let range = Range(range, in: string) else { return false }
let updatedString = textString.replacingCharacters(in: range, with: string)
let correctDecimalString = updatedString.replacingOccurrences(of: ",", with: ".")
let completeString = correctDecimalString.replacingOccurrences(of: formatter.groupingSeparator, with: "")
guard completeString.count <= 12 else { return false }
guard !completeString.isEmpty else { return true }
textField.text = completeString
return string == formatter.decimalSeparator
}
Custom NumpadView:
class NumpadView: UIView {
var target: UITextInput?
init(target: UITextInput) {
super.init(frame: .zero)
self.target = target
initializeSubview()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
initializeSubview()
}
func initializeSubview() {
let xibFileName = "NumpadView"
let view = Bundle.main.loadNibNamed(xibFileName, owner: self, options: nil)![0] as! UIView
self.addSubview(view)
view.frame = self.bounds
self.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
@IBAction func buttonPressed(_ sender: NumpadButton) {
insertText((sender.titleLabel!.text)!)
}
func insertText(_ string: String) {
guard let range = target?.selectedRange else { return }
if let textField = target as? UITextField, textField.delegate?.textField?(textField, shouldChangeCharactersIn: range, replacementString: string) == false {
return
}
target?.insertText(string)
}
}
extension UITextInput {
var selectedRange: NSRange? {
guard let selectedRange = selectedTextRange else { return nil }
let location = offset(from: beginningOfDocument, to: selectedRange.start)
let length = offset(from: selectedRange.start, to: selectedRange.end)
return NSRange(location: location, length: length)
}
}
2.How I initialize it in a VC:
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self
textField.inputView = NumpadView(target: textField)
}
Test project on GitHub: CLICK
What should I do so the code in shouldChangeCharactersIn method work for my custom Numpad?
Post not yet marked as solved
I have an App that connects to an IOT device via Bluetooth. I gave it the proper permissions in the info.plist file, and it works fine when I run it from XCode, is able to connect to and communicate with the IOT device via bluetooth. However, when I installed the App on another device via TestFlight, it does not work despite having all the same permissions and the exact same code. I do not know how to debug it since in Dev it works fine. Does anyone have any idea how I can track down what is happening?
Post not yet marked as solved
Hi,
I was testing the lockdown mode in iOS 16 and would like to know whether we can detect the lockdown mode status using any public API that Apple provides.
I really appreciate any help you can provide.