Swift is a powerful and intuitive programming language for Apple platforms and beyond.

Posts under Swift tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Arabic Text Glitches With PageTabViewStyle
So I have the default language of my app as Arabic so everything goes from RTL but when I changed the default language to Arabic I started encountering this issue that happens when navigating from one view to another view. This issue shows the text inverted in a weird way. here is the image: https://imgur.com/amI8afA (note that this issue goes away if the TabView is not PageTabViewStyle)
1
0
340
Oct ’23
UserDefaults not cleared after Uninstall
Hi, We assume that when uninstalling an application, the UserDefaults are deleted. Starting iOS16 we encounter complaints from clients that this is not the case. We have succeeded in debugging a device where this occurred (UserDefaults were not deleted after uninstall+install), but have not succeeded in recreating this issue on another device. We assume this issue has a connection to iCloud sync, although UserDefaults iCloud synching should be specifically set up (using NSUbiquitousKeyValueStore) which we have NOT set. Or maybe it has to do with Family Sharing. We are initializing the UserDefaults with suiteName for usage in widgets, but assume this has not connection to the bug.
6
0
4.5k
Dec ’23
Regex literals in Swift Packages
So far I'm unable to use Regex literals in my Swift Packages. Xcode simply gives a syntax error and has no idea I'm trying to do Regex. This is with Xcode 14.1 and all the platforms in the Package.swift have been set to the minimum requirement (iOS 16, macOS 13, etc) as well as the swift-tools-version set to 5.7. Using the Regex type directly (try Regex("[a-z]")) does work. It's just the literals that Xcode refuses to recognize. Regex literals do work in app projects and playgrounds. Is there a setting in the Package.swift or something I'm forgetting? Thanks in advance!
2
0
1.6k
Oct ’23
Swift: Save image with file name using PHPhotoLibrary and PHAssetCreationRequest
I  am trying to save an image to the user's photo library using PHPhotoLibrary and set the image file name at the time of saving suing the code below. This is working the first time, but if I then try to save the same image again with a different file name, it saves with the same file name as before. Is there something I need to add to let the system know to save a new version of the image with a new file name? Thank you PHPhotoLibrary.shared().performChanges ({ let assetType:PHAssetResourceType = .photo let request:PHAssetCreationRequest = .forAsset() let createOptions:PHAssetResourceCreationOptions = PHAssetResourceCreationOptions() createOptions.originalFilename = "\(fileName)" request.addResource(with: assetType, data: image.jpegData(compressionQuality: 1)!, options: createOptions) }, completionHandler: { success, error in if success == true && error == nil { print("Success saving image") } else { print("Error saving image: \(error!.localizedDescription)") } })
3
0
2k
Aug ’23
1 minute Delay in External Accessory framework showBluetoothAccessoryPicker
I have to pair the classic Bluetooth device with my iOS application. For that, I have implemented showBluetoothAccessoryPicker with the External Accessory framework. EAAccessoryManager.shared().showBluetoothAccessoryPicker(withNameFilter: nil)), this is the code I have used for that. Added "Supported external accessory protocols" in .plist and enabled Wireless Accessory Configuration from capabilities. The actual issue is the picker displaying the device to pair with a 1-minute delay. What is the reason behind this reason and how can we resolve that?
1
0
883
Oct ’23
When set live activity dismissalPolicy: .after(endTime), the dynamic island not working
I have app that shows live activity and countdown till a date... VStack { Text("Countdown till You finish your homework")  Text(countdownTime, style: .timer) } After the time up, the live activity countup, the solution is to update the live activity via backgroundTask and this not always working, really apple sometimes fire the backgroundTask after hours. Another solution is to set dismissalPolicy: .after(countdownTime), but once I did that the dynamic island not working and the activity status is ended after right calling... await activity.end(using: state, dismissalPolicy: .after(countdownTime)) Can anyone help please, users feed back is why you we still see the old task on live activity. How come I can not update live activity? and how come if you set dismissalPolicy .after apple changes the activity status to ended and stop showing the dynamic island?
3
4
1.4k
Mar ’24
After iOS 16.1 Widgets + Extensions get the local form device language not from the app
Before iOS 16.1 my app was woking good, if the user set the app language to other language than his device language, my app, widget + extensions all use this language... After iOS 16.1 if user set the app language to other language than his device language, my app works with this language but the widget + extensions works with the device language, not my app language... For Example:     @Environment(\.locale.languageCode) private var userLocal before iOS 16.1 userLocal would be the app local, after iOS 16.1 it return the device local Any idea why Apple did that? is this a bug? How to set the widget language to match my app language now? even set .environment(\.locale, dose not work when use Strings(table: because it's still get the bundle that match device language.
3
2
1.4k
Apr ’24
[Swift error] process exited with signal SIGILL
I tried to use swift to solve an algorithm problem, but it gave me an error Problem Link: https://leetcode.com/problems/number-of-matching-subsequences/ class Solution { func bisect_right(arr: [Int], num: Int) -> Int { var l = 0, r = arr.count - 1 while l < r { var m = (l+r) / 2 if arr[m] <= num { l = m + 1 } else { r = m } } return l } func numMatchingSubseq(_ s: String, _ words: [String]) -> Int { var pos: [Character: [Int]] = [:] for (i, c) in s.enumerated() { pos[c]!.append(i) } var cnt = 0 for word in words { var prev = -1, ok = true for c in word { let ps = pos[c]! var res = bisect_right(arr: ps, num: prev) if res == ps.count { ok = false; break } prev = ps[res] } if ok { cnt += 1 } } return cnt } } i.e. s= "abcde" words = ["a","bb","acd","ace"]
1
0
1.3k
Aug ’23
WARNING: Application performed a reentrant operation in its NSTableView delegate. This warning will become an assert in the future.
Can anyone help to understand what is causing this warning message on this SampleCode. it happens when data in table gets updated it happens when I have lot of items in table and search for lets say # 6543 and then clear the search. "WARNING: Application performed a reentrant operation in its NSTableView delegate. This warning will become an assert in the future." If there are just few items in table, the warning is not there. And it started when updated to Xcode Version 14 and upward import SwiftUI import Foundation @main struct TestProjectSWIFTApp: App {     @StateObject var mydata: MyData = MyData()     var body: some Scene {         WindowGroup {             ContentView()                 .environmentObject(mydata)         }              } } struct ContentView: View {     @EnvironmentObject var mydata: MyData     var body: some View {         NavigationView{             NavigationLink("TABLE",  destination: MyTable())                      }     } } struct User: Identifiable {     let id: UUID = UUID()     var name: String     var score: Int } struct MyTable: View {     @EnvironmentObject var mydata: MyData     @State private var sortOrder = [KeyPathComparator(\User.name)]     @State var searchText: String = ""     var searchResults : [User] {         if searchText.isEmpty {             return mydata.alldata         } else {             return mydata.alldata.filter{$0.name.localizedCaseInsensitiveContains(searchText)}         }     }          var body: some View {                  Button("Generate new data", action: {             mydata.updateTable()         })                  Table(searchResults, sortOrder: $sortOrder) {             TableColumn("Score"){                 Text("\(Double($0.score))")             }             TableColumn("user", value: \.name)         }         .onChange(of: sortOrder) {             mydata.alldata.sort(using: $0)         }         .searchable(text: $searchText)     } } @MainActor class MyData : ObservableObject{     @Published var alldata: [User] = []               init(){         self.setData()     }          func setData(){         alldata = [             User(name: "User 1", score: 95),             User(name: "User 2", score: 80),             User(name: "User 3", score: 85)         ]     }          func updateTable(){         var newallData: [User] = []         var x = 0         while x < 10000{             newallData.append(User(name: "User #\(x)", score:  Int.random(in: 10..<999999)))                          x = x + 1         }         alldata = newallData     }      }
16
5
2.9k
Sep ’23
DriverKit | Memory limitations of AsyncCallback
We implemented communication between Swift App and DriverKit driver using IOConnectCallAsyncStructMethod. void USBDriverClass::registerAsyncCallback(){   // Async required variables   notificationPort = NULL;   machNotificationPort = NULL;   runLoopSource = NULL;       // Async initialization   globalRunLoop = CFRunLoopGetMain();   CFRetain(globalRunLoop);       notificationPort = IONotificationPortCreate(kIOMainPortDefault);   if (notificationPort == NULL)   {     printf("Failed to create notification port for application.\n");   }       machNotificationPort = IONotificationPortGetMachPort(notificationPort);   if (machNotificationPort == 0)   {     printf("Failed to get mach notification port for application.\n");   }       runLoopSource = IONotificationPortGetRunLoopSource(notificationPort);   if (runLoopSource == NULL)   {     printf("Failed to get run loop for application.\n");   }       // Establish our notifications in the run loop, so we can get callbacks.   CFRunLoopAddSource(globalRunLoop, runLoopSource, kCFRunLoopDefaultMode);       // Establish our "AsyncCallback" function as the function that will be called by our Dext when it calls its "AsyncCompletion" function.   // We'll use kIOAsyncCalloutFuncIndex and kIOAsyncCalloutRefconIndex to define the parameters for our async callback   // This is your callback function. Check the definition for more details.   asyncRef[kIOAsyncCalloutFuncIndex] = (io_user_reference_t)AsyncCallback;   // Use this for context on the return. For example you might pass "this". But since this example is entirely static, we'll skip that step.   asyncRef[kIOAsyncCalloutRefconIndex] = (io_user_reference_t)NULL;       kern_return_t ret = kIOReturnSuccess;   uint8_t words = 4;       size_t inputSize = sizeof(StructA);   StructA structA;       structA.tag = 1;   structA.length = 0;   structA.values[0] = 0x106000;   structA.values[1] = words * sizeof(uint32_t);       size_t outputSize = sizeof(OutputData);   OutputData data;   printf("registerAsyncCallback called");       ret = IOConnectCallAsyncStructMethod(connection, MessageType_RegisterAsyncCallback, machNotificationPort, asyncRef, kIOAsyncCalloutCount, &structA, inputSize, &data, &outputSize);   if (ret != kIOReturnSuccess)   {     printf("IOConnectCallAsyncStructMethod failed with error: 0x%08x.\n", ret);   } } And when we get data from device we send data back from Driver to Swift app ivars->mUSBProbeDriverClient->AsyncCompletion(ivars->streamingDataCallback, kIOReturnSuccess, asyncData, 16); Driver should transfer data to swift app asynchronously when it's provided by USB device so we can not transfer struct synchronously. Async call back has limitation of 16 of uint64_t only and our application require larger data transfer. The logical way to transfer data using a memory buffer and as per Apple documentation they are providing this using IODataQueueDispatchSource. But they have not provided any example or showed how to use this. How to use fill buffer and use it in swift app using IODataQueueDispatchSource?
1
1
1.1k
Nov ’23
@Environment(\.dismiss) var dismiss - Infinite loop bug.
The following code works: struct SelectBatteryChemistryView: View {     @ObservedObject var model: SelectBatteryChemistryViewModel = .init()     @Environment(\.presentationMode) private var presentationMode     var body: some View {         VStack {             Spacer()             TitleText("BATTERY MODE")             SimpleModeSelectorView(                 selected: $model.batteryChemistry             )             .pickerStyle(.inline)             .frame(minHeight: 300)             PrimaryTitleButton(title: "SELECT") {                 if model.batteryChemistry == .user {                     model.customChemistryFlow = true                 } else {                     model.confirmBatterySettings()                 }             }             NavigationLink(                 destination: CustomBatteryChemistryView(),                 isActive: $model.customChemistryFlow             ) { EmptyView() }                 .isDetailLink(false)         }         .onReceive(model.$batterySettingsConfirmed) { batterySettingsConfirmed in             if batterySettingsConfirmed {                 //dismiss()             }         }         .onAppear() {             model.customChemistryFlow = false         }     } } The following code causes an infinite loop in the CustomBatteryChemistryView() initialiser. struct SelectBatteryChemistryView: View {     @ObservedObject var model: SelectBatteryChemistryViewModel = .init()     @Environment(\.dismiss) private var dismiss     var body: some View {         VStack {             Spacer()             TitleText("BATTERY MODE")             SimpleModeSelectorView(                 selected: $model.batteryChemistry             )             .pickerStyle(.inline)             .frame(minHeight: 300)             PrimaryTitleButton(title: "SELECT") {                 if model.batteryChemistry == .user {                     model.customChemistryFlow = true                 } else {                     model.confirmBatterySettings()                 }             }             NavigationLink(                 destination: CustomBatteryChemistryView(),                 isActive: $model.customChemistryFlow             ) { EmptyView() }                 .isDetailLink(false)         }         .onReceive(model.$batterySettingsConfirmed) { batterySettingsConfirmed in             if batterySettingsConfirmed {                 //dismiss()             }         }         .onAppear() {             model.customChemistryFlow = false         }     } } Adding the @Environment(.dismiss) object prevents the use of a navigation link. The program sits there with the stack infinitely calling the getter for the NavigationLink. It looks like an infinite loop on the accessor due to some strangeness related to the magic of the Dismiss environment object. How do we pass this on to the Dev team at Apple?
9
5
2.2k
Jan ’24
Problem with GeometryReader
Hello, I used GeometryReader to proportion the size of my Frames vertically regardless of the device. Yet the List on the Ipad contains 3 lines and only 1 on the Iphone. Where is my error in the code for this layout? Thanks in advance             GeometryReader { geo in                 VStack(spacing: 0){                     Text(getTimeString(m: self.minutes, s: self.seconds, c: self.centiseconds))                         .font(.system(size: min(geo.size.height, geo.size.width) * 0.05, design: .monospaced))                         .frame(height: UIScreen.main.bounds.height * 0.05)                         .onReceive(timer) {_ in                             if(self.running) {                                 self.timerCalcs()                             }                         }                                          Text("\(lapCount - 1)")                         .font(.system(size: min(geo.size.height, geo.size.width) * 0.25))                         .fontWeight(.bold)                         .frame(height: UIScreen.main.bounds.height * 0.25)                         .foregroundColor(.red)                                          ZStack {                         Text(self.lapTimes.last?.getLapSecondsString() ?? "")                             .font(.system(size: min(geo.size.height, geo.size.width) * 0.45))                             .fontWeight(.bold)                             .frame(height: UIScreen.main.bounds.height * 0.38)                         Rectangle().fill(Color.gray.opacity(0.1))                     }                                          HStack(spacing : 10){                             Button(action: {                                 if(!self.running) {                                     self.minutes = 0                                     self.seconds = 0                                     self.centiseconds = 0                                     self.lapTimes = []                                     self.lapMinutes = 0                                     self.lapSeconds = 0                                     self.lapCentiseconds = 0                                     self.lapCount = 1                                                                      } else {                                     self.lapTimes.append(LapTime(n: self.lapCount, m: self.lapMinutes, s: self.lapSeconds, c: self.lapCentiseconds))                                     self.lapCount += 1                                     self.lapMinutes = 0                                     self.lapSeconds = 0                                     self.lapCentiseconds = 0                                 }                             }) {                                 ZStack{                                     Circle().fill(Color.gray).frame(height: UIScreen.main.bounds.height * 0.12)                                     self.running ? Text("Lap").foregroundColor(Color.white).font(.system(size: min(geo.size.height, geo.size.width) * 0.04, design: .monospaced)) : Text("Reset").foregroundColor(Color.white).font(.system(size: min(geo.size.height, geo.size.width) * 0.04, design: .monospaced))                                 }                             }                             .padding(8)                             Spacer()                             Button(action: {                                 self.running = !self.running                             }) {                                 ZStack{                                     Circle().fill(self.running ? Color.red : Color.green).frame(height: UIScreen.main.bounds.height * 0.12).font(.system(size: min(geo.size.height, geo.size.width) * 0.04, design: .monospaced))                                     self.running ? Text("Stop").foregroundColor(Color.white).font(.system(size: min(geo.size.height, geo.size.width) * 0.04, design: .monospaced)) : Text("Start").foregroundColor(Color.white).font(.system(size: min(geo.size.height, geo.size.width) * 0.04, design: .monospaced))                                 }                             }                             .padding(8)                     }                                                                                        List{                         LapTime(n: self.lapCount, m: self.lapMinutes, s: self.lapSeconds, c: self.lapCentiseconds)                         ForEach(self.lapTimes.reversed()) { time in                             time                                                          }                        }                 }             }                      }
6
0
1.8k
Sep ’23
compareDistance in Vision not working as expected
Hi, When using VNFeaturePrintObservation and then computing the distance using two images, the values that it returns varies heavily. When two identical images (same image file) is inputted into function (below) that I have used to compare the images, the distance does not return 0 while it is expected to, since they are identical images. Also, what is the upper limit of computeDistance? I am trying to find the percentage similarity between the two images. (Of course, this cannot be done unless the issue above is resolved). Code that I have used is below func featureprintObservationForImage(image: UIImage) -> VNFeaturePrintObservation? {     let requestHandler = VNImageRequestHandler(cgImage: image.cgImage!, options: [:])     let request = VNGenerateImageFeaturePrintRequest()     request.usesCPUOnly = true // Simulator Testing     do {       try requestHandler.perform([request])       return request.results?.first as? VNFeaturePrintObservation     } catch {       print("Vision Error: \(error)")       return nil     }   }   func compare(origImg: UIImage, drawnImg: UIImage) -> Float? {     let oImgObservation = featureprintObservationForImage(image: origImg)     let dImgObservation = featureprintObservationForImage(image: drawnImg)     if let oImgObservation = oImgObservation {       if let dImgObservation = dImgObservation {         var distance: Float = -1         do {           try oImgObservation.computeDistance(&distance, to: dImgObservation)         } catch {           fatalError("Failed to Compute Distance")         }         if distance == -1 {           return nil         } else {           return distance         }       } else {         print("Drawn Image Observation found Nil")       }     } else {       print("Original Image Observation found Nil")     }     return nil   } Thanks for all the help!
4
1
1.9k
Sep ’23
DeviceActivityMonitor - intervalDidStart() not able to restrict apps/categories/webCategories
I've followed along with the Screen Time API demos (https://developer.apple.com/videos/play/wwdc2021/10123/) Also followed along with this guide, which is essentially the same: https://www.folio3.com/mobile/blog/screentime-api-ios/ I'm able to restrict access to apps/categories with the FamilyActivityPicker and FamilyActivitySelection. I can set a DeviceActivitySchedule, and then use DeviceActivityCenter to start monitoring it. I can tell that the schedule is working, because MyMonitor:intervalDidStart() does get called, and it works except for the restricting of apps/categories/webCategories. It's as if MyModel does not have any values set from within MyMonitor. I've confirmed that MyModel does have the correct FamilyActivitySelection apps etc, everywhere else in my Target, before and after the MyMonitor:intervalDidStart() gets called. MyMonitor is in a separate target called MonitorExtension, that I created using the Device Activity Monitor Extension template. But I made sure to set the Target Membership of MyModel to both my main target, and my extension target. I have set NSExtensionPrincipalClass to $(PRODUCT_MODULE_NAME).MyMonitor, as suggested. I have added MyModel.swift to the Compiled Sources in my extensions Build Phases. I have edited my apps build scheme, to make sure the extension target is also built. One more interesting thing is that debugger breakpoints and print statements do not work from within my extension. I've even tried caching a string from within MyMonitor:intervalDidStart, and tried to retrieve it afterwards in my main target, but it is nil. Still, I've confirmed that intervalDidStart was actually called by adding any removing store.application.denyAppInstallation = true, and having it work correctly. I've spent so much time on this problem, any help would be massive.. Here are the files I've referenced: import UIKit import MobileCoreServices import ManagedSettings import DeviceActivity class MyMonitor: DeviceActivityMonitor {   let store = ManagedSettingsStore()   override func intervalDidStart(for activity: DeviceActivityName) {     super.intervalDidStart(for: activity)     let model = MyModel.shared     let applications = model.selectionToDiscourage.applicationTokens     let categories = model.selectionToDiscourage.categoryTokens     let webCategories = model.selectionToDiscourage.webDomainTokens          if applications.isEmpty {      print("No applications to restrict")     } else {      store.shield.applications = applications     }          if categories.isEmpty {      print("No categories to restrict")     } else {      store.shield.applicationCategories = ShieldSettings.ActivityCategoryPolicy.specific(categories, except: Set())     }          if webCategories.isEmpty {      print("No web categories to restrict")     } else {      store.shield.webDomains = webCategories     }     store.dateAndTime.requireAutomaticDateAndTime = true     store.account.lockAccounts = true     store.passcode.lockPasscode = true     store.siri.denySiri = true     store.appStore.denyInAppPurchases = true     store.appStore.maximumRating = 200     store.appStore.requirePasswordForPurchases = true     store.media.denyExplicitContent = true     store.gameCenter.denyMultiplayerGaming = true     store.media.denyMusicService = true     store.application.denyAppInstallation = true   }   override func intervalDidEnd(for activity: DeviceActivityName) {     super.intervalDidEnd(for: activity)     store.shield.applications = nil     store.shield.applicationCategories = nil     store.shield.webDomains = nil     store.dateAndTime.requireAutomaticDateAndTime = false     store.account.lockAccounts = false     store.passcode.lockPasscode = false     store.siri.denySiri = false     store.appStore.denyInAppPurchases = false     store.appStore.maximumRating = 1000     store.appStore.requirePasswordForPurchases = false     store.media.denyExplicitContent = false     store.gameCenter.denyMultiplayerGaming = false     store.media.denyMusicService = false     store.application.denyAppInstallation = false   } } import Foundation import FamilyControls import DeviceActivity import ManagedSettings class MyModel: ObservableObject {   static let shared = MyModel()   let store = ManagedSettingsStore()   private init() {}   var selectionToDiscourage = FamilyActivitySelection() {     willSet {       let applications = newValue.applicationTokens       let categories = newValue.categoryTokens       let webCategories = newValue.webDomainTokens       store.shield.applications = applications.isEmpty ? nil : applications       store.shield.applicationCategories = ShieldSettings.ActivityCategoryPolicy.specific(categories, except: Set())       store.shield.webDomains = webCategories      }   }   func initiateMonitoring(scheduleStart: DateComponents, scheduleEnd: DateComponents) {     let schedule = DeviceActivitySchedule(intervalStart: scheduleStart, intervalEnd: scheduleEnd, repeats: true, warningTime: nil)     print(scheduleStart)     print(scheduleEnd)     let center = DeviceActivityCenter()     do {       try center.startMonitoring(.daily, during: schedule)     }     catch {       print ("Could not start monitoring \(error)")     }          store.dateAndTime.requireAutomaticDateAndTime = false     store.account.lockAccounts = false     store.passcode.lockPasscode = false     store.siri.denySiri = false     store.appStore.denyInAppPurchases = false     store.appStore.maximumRating = 1000     store.appStore.requirePasswordForPurchases = false     store.media.denyExplicitContent = false     store.gameCenter.denyMultiplayerGaming = false     store.media.denyMusicService = false     store.application.denyAppInstallation = false   } } extension DeviceActivityName {   static let daily = Self("daily") } import SwiftUI import FamilyControls struct AppPicker: View {   @StateObject var model = MyModel.shared   @State var isPresented = false       var body: some View {     Button("Select Apps to Discourage") {       isPresented = true     }     .familyActivityPicker(isPresented: $isPresented, selection: $model.selectionToDiscourage)   } }
8
0
1.9k
Oct ’23
Does setAlternateIconName work in mac Catalyst?
I'm trying to change app icon on Dock in macOS from my app. But couldn't get to work. The setAlternateIconName works fine in iOS simulator, but when I run in on my mac (Catalyst) I got this error: The requested operation couldn’t be completed because the feature is not supported. Apple Doc - https://developer.apple.com/documentation/uikit/uiapplication/2806818-setalternateiconname Thank you
1
1
845
May ’24
WeatherKit Swift / REST mismatch? daytimeForecast and overnightForecast not available via Swift?
I am able to obtain daily forecasts via the REST API which include the daytimeForecast and overnightForecast records with their respective properties like cloudCover. So far I have failed to access them via the Swift API: forecast.daytimeForecast.cloudCover results in: "Value of type 'DayWeather' has no member 'daytimeForecast'". But if I print() the DayWeather objects, these members are actually printed with all their properties. Is there a way to get them I am overlooking?
2
0
1.6k
Jul ’23
Developer Mode setting missing on iPhone
This is the first time I’ve tried to run an Xcode app on my iPhone. To do this, the iPhone must have “Developer Mode” enabled but this settings was not visible on my iPhone. I searched the blog and did not find a suitable solution. Eventually, I got it working so wanted to publish my findings. I am documenting this after trying many things so I am not 100% sure of the magic formula, but “I think” this is what is needed. PROBLEM iPhone -> Settings -> Privacy & Security -> Developer Mode (NOT VISIBLE) ENVIRONMENT iPhone 12 Pro Max running IOS 16.2 MacBook Pro running macOS 12.5.1 Xcode 14.2 CONNECT IPHONE TO MAC (via USB cable) CHECK DEVICE STATUS (in Xcode) Select menu Window -> Devices and Simulators You should see your iPhone but it will show warnings/issues. (e.g. device not in Developer Mode) ADD APPLE ID (in Xcode)  Open your app project in Xcode Select menu Xcode -> Preferences Select Accounts tab Add your Apple ID (It will be listed as a “Personal Team”) SELECT IPHONE AS DESTINATION (in Xcode)  Select menu Product -> Destination -> Choose Destination In the “IOS Device” section, select your iPhone as the destination (NOTE: After doing this, the “Developer Mode” setting was available on my iPhone) iPhone -> Settings -> Privacy & Security -> Developer Mode (Now visible) SELECT DEVELOPER MODE (on iPhone) Settings -> Privacy & Security -> Developer Mode (ENABLE) SELECT APPLE ID AS TEAM (in Xcode)  Select your project in the Project Navigator Select the project in the TARGETS section Select “Signing & Capabilities” tab In the “Signing” section, select the Team as your Apple ID (you previously entered) After this, I had an error and need to modify the “Bundle Identifier” to make it unique. I just added some numbers to the end and it worked. CHECK. DEVICE STATUS (in Xcode)  Select menu Window -> Devices and Simulators This time, your iPhone should appear without any warnings/issues. LOAD APP ONTO IPHONE (in Xcode)  Hit the arrow in Xcode to Start the active scheme. (The App will be loaded onto your iPhone.) RUN APP (on iPhone) Try running the app and the iPhone will not allow it since you have not authorized apps from this developer. Goto Settings -> General -> VPN & Device Management Authorize your Apple ID to run apps on this phone. You should now be able to run the app without issue.
3
0
9.1k
Jul ’23
await UIApplication.shared.beginBackgroundTask inside an async method
Looking for tips here. I've got Swift Concurrency Checking set to Complete - so I'm seeing interesting warnings that I'd like to hear what the proper way to fix this is. I've got an async method that I'm using in a variety of places that I need to specify is a task that needs to complete even if the user goes into the background. It can take 2-60 seconds depending on DNS/network and server responses. func checkRoutineDepartures() async {         var bgTaskId: UIBackgroundTaskIdentifier = .invalid         bgTaskId = await UIApplication.shared.beginBackgroundTask(withName: "checkRoutineDepartures") {             UIApplication.shared.endBackgroundTask(bgTaskId)             bgTaskId = .invalid         } With the complete option, I get a warning Non-sendable type '(() -> Void)?' passed in call to main actor-isolated function cannot cross actor boundary on the completion handler and then on the endBackgroundTask line I get Call to main actor-isolated instance method 'endBackgroundTask' in a synchronous nonisolated context; this is an error in Swift 6 In the docs for both of these, it says I can call them This method can be safely called on a non-main thread. So it seems to me like the headers are incorrectly marking the entire class as Main Actor and missing these methods, or I'm doing something wrong.
2
4
933
Aug ’23
WeatherKit Gives 404
When I'm using the following code into the simulator it gives the wanted result: Button {                 Task {                     localWeather = try await WeatherService.shared.weather(for: CLLocation(latitude: 52.5153, longitude: 6.08565), including:  .daily(startDate: Date(), endDate: Calendar.current.date(byAdding: .day, value: 1, to: Date())!)).first.debugDescription                 }             } label: {                 Text("Get the test weather")             }             Text(localWeather) When I'm using this exact code on a real device I get the following 404 error: [WeatherDataService] Received invalid http response code 404 for request: C7AEC7CC-E5F7-425D-8491-25B9302E2A0F:0 [WeatherService] Encountered an error when fetching weather data subset; location=<+52.51530000,+6.08565000> +/- 0.00m (speed -1.00 mps / course -1.00) @ 05/01/2023, 13:55:53 Central European Standard Time,  error=responseFailed(<NSHTTPURLResponse: 0x282ce0260> { URL: https://weather-data.apple.com/v3/weather/en/52.515/6.086?timezone=Europe/Amsterdam&dataSets=forecastHourly,forecastDaily&dailyStart=2023-01-10T12:00:00Z&dailyEnd=2023-01-10T12:00:00Z&hourlyStart=2023-01-10T11:00:00Z&hourlyEnd=2023-01-10T16:00:00Z&country=NL } { Status Code: 404, Headers {     "Access-Control-Allow-Origin" =     (         "*"     );     "Cache-Control" =     (         "max-age=0, no-cache, no-store"     );     Connection =     (         "keep-alive"     );     "Content-Length" =     (         0     );     "Content-Security-Policy" =     (         "default-src 'self';"     );     Date =     (         "Thu, 05 Jan 2023 12:59:27 GMT"     );     Expires =     (         "Thu, 05 Jan 2023 12:59:27 GMT"     );     Pragma =     (         "no-cache"     );     Server =     (         "AppleHttpServer/21be5247c6351682d1d9aa22fe98c8f0d4902838"     );     "Strict-Transport-Security" =     (         "max-age=31536000; includeSubDomains",         "max-age=31536000"     );     "X-Apple-Origin" =     (         "bcd49c7f-c567-3921-a041-3d4ef58e5423"     );     "X-B3-TraceId" =     (         c8c6547722afc53f     );     "X-Cache" =     (         "TCP_MISS from a104-110-190-91.deploy.akamaitechnologies.com (AkamaiGHost/10.10.3-45298580) (-)"     );     "X-Content-Type-Options" =     (         nosniff     );     "X-Frame-Options" =     (         DENY     );     "X-REQUEST-ID" =     (         "407e37bc-ddf6-45fd-84d0-1d3d3b8651b0"     );     "X-XSS-Protection" =     (         "1; mode=block"     ); } }, Optional("")) I fixed it once by deleting Xcode and the app from my iPhone, but that doesn't work anymore. Any suggestions?
3
3
1.4k
Dec ’23
AsyncPublisher of KeyValueObservingPublisher doesn't work
Hi, I'm trying to use async/await for KVO and it seems something is broken. For some reason, it doesn't go inside for in body when I'm changing the observed property. import Foundation import PlaygroundSupport class TestObj: NSObject {   @objc dynamic var count = 0 } let obj = TestObj() Task {   for await value in obj.publisher(for: \.count).values {     print(value)   } } Task.detached {   try? await Task.sleep(for: .microseconds(100))   obj.count += 1 } Task.detached {   try? await Task.sleep(for: .microseconds(200))   obj.count += 1 } PlaygroundPage.current.needsIndefiniteExecution = true Expected result: 0, 1, 2 Actual result: 0 Does anyone know what is wrong here?
2
1
2.1k
Feb ’24