Post

Replies

Boosts

Views

Activity

Swift Timer How to invoke timer calls when app goes off-line
I have timer based code running perfectly when the app is running. Both the timer based functions get called and I am able to access and update iCloud. But if accidentally app goes off-line or user kills it, the timer code cannot be invoked. Is there a off-line mechanism, or some technique anyone can suggest that will allow to recollect and invoke pre-defined timer calls and execute the associated code? let currentDateTime = Date() let calendar = Calendar.current var tempDateTime1 = calendar.date(byAdding: .minute, value: 1, to: currentDateTime) var tempDateTime2 = calendar.date(byAdding: .minute, value: 2, to: currentDateTime) DispatchQueue.main.async { let userInfo:Dictionary<String, String> = ["tag": orderCkRecordName] let startTimer = Timer(fireAt: tempDateTime1!, interval: 0.0, target: self, selector: #selector(self.beginOrderUpdate(sender:)), userInfo: userInfo as Dictionary, repeats: false) let endTimer = Timer(fireAt: tempDateTime2!, interval: 0.0, target: self, selector: #selector(self.endOrderUpdate(sender:)), userInfo: userInfo as Dictionary, repeats: false) RunLoop.current.add(startTimer, forMode: RunLoopMode.commonModes) RunLoop.current.add(endTimer, forMode: RunLoopMode.commonModes) }
0
0
703
Feb ’22
NSPersistentCloudKitContainer - creates CD_ CKRecord but does not populate values
I have a working app with core data and cloudkit. I changed the NSPersistentContainer to NSPersistentCloudKitContainer. Two NSManagedObjects 'Contact' and 'Location' already exist in core data with relationships along with some other related NSManagedObjects. Populated core data in 'Contact' and saved. Logged in to CloudKit to see it had created CD_Contact and CD_Location CKRecords along with some other CKRecords. Queried CD_Contact it gave error - index name not available on recordName. So created an Index of type Queryable on recordName and searched again. There is no data in CD_Contact. It is supposed to sync data from core data to cloud Kit, but only CKRecord is created but data saved in core data is not synced and populated in CloudKit. How to fix this? On debug I get this:   "<CKRecord: 0x104f0afc0; recordType=CD_Contact, recordID=558FD3FB-A293-444C-8894-A1A7B786D73A:(com.apple.coredata.cloudkit.zone:__defaultOwner__), recordChangeTag=15, values={\n  \"CD_assignedEEP\" = 0;\n  \"CD_createdDate\" = \"2022-11-03 04:14:17 +0000\";\n  \"CD_email\" = \"crsp@gmail\";\n  \"CD_entityName\" = Contact;\n  \"CD_firstName\" = chaya;\n  \"CD_imageName\" = \"{ length=87143, sha256=ed66d0026ea41aed08e213928643398504dea984c010b80a8852a0fb72c80350 }\";\n  \"CD_lastName\" = rao;\n  \"CD_me\" = 0;\n  \"CD_orgName\" = \"\";\n  \"CD_phone\" = 8327292039;\n  \"CD_screenName\" = cvr;\n  \"CD_uniqueId\" = \"A2469E8D-782F-49F5-8186-3C38B8F9B715-55813-00001051FEDEEF2F\";\n  \"CD_userRating\" = \"Not rated\";\n  \"CD_userType\" = \"Consumer & Producer(Household)\";\n}>",   "CD_contactEmail" = "crsp@gmail";   "CD_contactEmail_ckAsset",   "CD_contact",   "CD_contactEmail",   "<CKRecord: 0x111659350; recordType=CD_Location, recordID=D6FA5778-587E-4778-925E-197AD5ABC66B:(com.apple.coredata.cloudkit.zone:__defaultOwner__), recordChangeTag=19, values={\n  \"CD_apt\" = \"\";\n  \"CD_assignedEEP\" = 0;\n  \"CD_batterykWh\" = 0;\n  \"CD_city\" = Houston;\n  \"CD_contactEmail\" = \"crsp@gmail\";\n  \"CD_country\" = US;\n  \"CD_entityName\" = Location;\n  \"CD_evkWh\" = 0;\n  \"CD_latitude\" = \"29.92885756496788\";\n  \"CD_loadWatts\" = 0;\n  \"CD_loadkWh\" = 0;\n  \"CD_locationName\" = myloc;\n  \"CD_locationType\" = Household;\n  \"CD_longitude\" = \"-95.60777006842892\";\n  \"CD_netMeterEsid\" = 1008901023808105650100;\n  \"CD_provider\" = \"AMIGO ENERGY\";\n  \"CD_providerType\" = \"Energy Provider\";\n  \"CD_solarkWh\" = 0;\n  \"CD_state\" = TX;\n  \"CD_street\" = \"11202 Hillside Glen Trail \";\n  \"CD_uniqueId\" = \"27D61490-B38A-4F0A-A5EC-76BDBDEBA46F-55813-00001052B902170C\";\n  \"CD_windkWh\" = 0;\n  \"CD_zip\" = 77065;\n}>" My AppDelegate Code: let container = NSPersistentCloudKitContainer(name: "MyModel") let defaultStoreURL = try! FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("MyModel.xcdatamodeld") let description = NSPersistentStoreDescription(url: defaultStoreURL) let cloudkitOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: "iCloud.com.ggp.nr") description.cloudKitContainerOptions = cloudkitOptions let remoteChangeKey = "NSPersistentStoreRemoteChangeNotificationOptionKey" description.setOption(true as NSNumber, forKey: remoteChangeKey) description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) container.persistentStoreDescriptions = [description] container.viewContext.automaticallyMergesChangesFromParent = true container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } // if FileManager.default.fileExists(atPath: self.storeURL.path) { // self.duplicateRecordsAndDeleteOldStore(newContext: container.newBackgroundContext(), mom: container.managedObjectModel) // } }) return container }() Also in my cloudKit database "iCloud.com.ggp.nr", under security roles for iCloud and World I have set Read and Write permissions for all the CD_ Records. Don't know what else to do. Any help is appreciated.
0
0
1k
Nov ’22
Configuring CoreData to CloudKit private database issues
Inside the core data database, I created new private configuration. Then Created a new entity which got added to default configuration. Dragged the new entity to the newly created private configuration. It crashes. Am I doing this right? If so is it Xcode 13.3.1 bug ? and should I upgrade? Once I get past this issue, will the below given load persistent stores code export/synchronize the new entity from core data private configuration to cloudkit private database?  container.loadPersistentStores(completionHandler: { (loadedStoreDescription, error) in       if let loadError = error as NSError? {         fatalError("###\(#function): Failed to load persistent stores:\(loadError)")       } else if let cloudKitContainerOptions = loadedStoreDescription.cloudKitContainerOptions {         if #available(iOS 14.0, *) {           if .public == loadedStoreDescription.cloudKitContainerOptions?.databaseScope {             self._publicPersistentStore = container.persistentStoreCoordinator.persistentStore(for: loadedStoreDescription.url!)           } else if .private == loadedStoreDescription.cloudKitContainerOptions?.databaseScope {             self._privatePersistentStore = container.persistentStoreCoordinator.persistentStore(for: loadedStoreDescription.url!)           }         } else {           // Fallback on earlier versions         }       }
0
0
819
Nov ’22
SwiftUI cannot fetch entity records
I am trying to get all records from Entity Location and pull the data from the entity to create a array of strings and display in a MenuPicker. In getLocationNames() ForEach statement it never pulls locations even though there are records. Also I do have a warning on that line: Result of 'ForEach<Data, ID, Content>' initializer is unused entity: Location.entity(), sortDescriptors: [NSSortDescriptor(key: "locationName", ascending: true)] ) var locations: FetchedResults<Location> @State private var locationNames: [String] = [] @State private var locationDetails:[String] = [] @State private var selectedLocation: String? = nil @State private var location: Location? = nil var body: some View { NavigationView { ScrollView (showsIndicators: false) { HStack { Text("Select Location") Picker("Location", selection: $selectedLocation , content: { ForEach(locationNames,id: \.self, content: { locationName in Text(locationName ) }) }) .pickerStyle(MenuPickerStyle()) .onReceive([self.selectedLocation].publisher.first()) { value in selectedLocation = value print("selectedLocation: \(selectedLocation ?? "not found")") } .onTapGesture { // self.callWeatherAPI(location: selectedLocation) self.getLocationNames() } Section{ if ($selectedLocation.wrappedValue != nil) { } } header: { Text("**Current Weather**") .padding(.top, 10) } } .navigationTitle("Weather") .toolbar { ToolbarItem(placement: .confirmationAction) { // Button("Save", action: { Task { try? await rI?(nameInput, phoneInput) } }) Button("Detail", action: { onAdd() } ) .foregroundColor(.blue) } } } .onAppear{ self.getLocationNames() } } } func getLocationNames() -> (Void){ ForEach(locations) { location in locationNames.append( self.getLocationString(location: location)) } } private func getLocationString(location: Location) -> String { var locDetails: String = location.locationType! + "; " locDetails += location.locationName! + ", " locDetails += location.zip! return locDetails } }
0
0
576
Jul ’23
How to loop and place map markers with MKAnnotationView
From core data I generate data for map marker pins. When user selects a marker pin I display the data in a popup label with multiple rows, when I click on the pin. This is working for one marker pin. Now, I need to iterate over a list and generate several of those markers each with unique popup label data. The code: struct MapView: UIViewRepresentable { var annotationOnTap: (_ title: String) -> Void @Binding var pins: [GpsData.MyEndPt] let key: String private static var mapViewStore = [String : MKMapView]() func makeUIView(context: Context) -> MKMapView { if let mapView = MapView.mapViewStore[key] { mapView.delegate = context.coordinator return mapView } let mapView = MKMapView(frame: .zero) mapView.delegate = context.coordinator MapView.mapViewStore[key] = mapView return mapView } func updateUIView(_ uiView: MKMapView, context: Context) { uiView.addAnnotations(pins) } func makeCoordinator() -> MapCoordinator { MapCoordinator(self) } final class MapCoordinator: NSObject, MKMapViewDelegate { var parent: MapView init(_ parent: MapView) { self.parent = parent } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { let PINID:String = "MyEndPoint" var mPin: MKMarkerAnnotationView? = nil let subtitleView = UILabel() subtitleView.font = subtitleView.font.withSize(12) subtitleView.numberOfLines = 0 if (mPin == nil ) { mPin = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: PINID) mPin?.canShowCallout = true } else{ mPin?.annotation = annotation } mPin?.leftCalloutAccessoryView = nil let btn = UIButton(type: .detailDisclosure) mPin?.rightCalloutAccessoryView = btn let zip:String = "77065" let formattedSalesStr:String = "100" let totalTargetText:String = "500" let paddedLoad = formattedSalesStr.padding(toLength: 50, withPad: " ", startingAt: 0) let paddedCapacity = totalTargetText.padding(toLength: 50, withPad: " ", startingAt: 0) subtitleView.text = "Total sales: " subtitleView.text! += paddedLoad subtitleView.text! += " \r\n" subtitleView.text! += "Total Target: " subtitleView.text! += paddedCapacity subtitleView.text! += " \r\n" subtitleView.text! += paddedzip mPin!.detailCalloutAccessoryView = subtitleView return mPin! } } } As you can see in the above method I have hardcoded values for my popup marker label. So I tried to iterate over the @Binding pins, populate each mPin, and return an array of MKAnnotationView, like this: func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> [MKAnnotationView] { let PINID:String = "MyEndPoint" var i:Int = 1 var mPins = [MKAnnotationView]() for detail in self.parent.pins { var mPin: MKMarkerAnnotationView? = nil let subtitleView = UILabel() subtitleView.font = subtitleView.font.withSize(12) subtitleView.numberOfLines = 0 if (mPin == nil ) { mPin = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: PINID) mPin?.canShowCallout = true } else{ mPin?.annotation = annotation } mPin?.leftCalloutAccessoryView = nil let btn = UIButton(type: .detailDisclosure) mPin?.rightCalloutAccessoryView = btn subtitleView.text! += String(i) subtitleView.text = "Total Load: " subtitleView.text! += String(detail.sales) subtitleView.text! += " \r\n" subtitleView.text! += "Total Target: " subtitleView.text! += String(detail.target) subtitleView.text! += " \r\n" i += 1 // } mPin!.detailCalloutAccessoryView = subtitleView mPins.append(mPin!) } return mPins } The marker pins show up, but then the label does not popup. How to fix this?
0
0
902
Feb ’24
How to navigate to a new view when MapView calloutAccessoryControlTapped method is called
What I am trying to accomplish: Navigate to MapView defined in ProfileMapView. - This works In ProfileMapView, when calloutAccessoryControlTapped method is called Navigate from ProfileMapView when to another view: ProfileDetailsView- This is does not work //Calling ProfileMapview like this: @State var pins = [GpsData.MyEndPt]() ProfileMapView(locationPins: $pins) // ProfileMapView defined struct ProfileMapView: View { @Environment(\.managedObjectContext) private var viewContext @Environment(\.dismiss) var dismiss @State var tracking:MapUserTrackingMode = .follow @Environment(\.presentationMode) var presentationMode @Binding var locationPins: [GpsData.MyEndPt] var body: some View { TabView { NavigationView { ZStack { VStack (alignment: .leading){ MapView(locationPins: $locationPins) .ignoresSafeArea() } } //.edgesIgnoringSafeArea(.all) .safeAreaInset(edge: .bottom) { Color.clear .frame(height: 0) .background(.white) } } } struct MapView: UIViewRepresentable { @Binding var locationPins: [GpsData.MyEndPt] func makeUIView(context: Context) -> MKMapView { //... } func updateUIView(_ uiView: MKMapView, context: Context) { //... } func makeCoordinator() -> MapViewDelegate{ var del = MapViewDelegate() del.addEndPoints(endPoints: locationPins) return del } class MapViewDelegate: MKMapView, MKMapViewDelegate { let PINID:String = "MyEndPoint" var mylocationPins: [GpsData.MyEndPt] = [] @State var locationId: String? @State var providerType: String? public func addEndPoints(endPoints: [GpsData.MyEndPt]) { self.mylocationPins = endPoints self.removeAnnotations(endPoints) self.addAnnotations(endPoints) self.showAnnotations(endPoints, animated: true) } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { var mPin: MKMarkerAnnotationView? = nil let subtitleView = UILabel() for pin in self.mylocationPins { if (mPin == nil ) { mPin = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: PINID) mPin?.canShowCallout = true } else{ mPin?.annotation = annotation } mPin?.rightCalloutAccessoryView = UIButton(type: UIButton.ButtonType.detailDisclosure) subtitleView.text = "Target: " subtitleView.text! += String(pin.target) } mPin!.detailCalloutAccessoryView = subtitleView return mPin! } func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { DispatchQueue.main.async { if let thumbnailImageButton = view.leftCalloutAccessoryView as? UIButton, let url = (view.annotation as? GpsData.MyEndPt)?.thumbnailUrl { print("URL: \(url)") do{ let imageData: Data = try Data(contentsOf: url as URL) let image = UIImage(data: imageData) thumbnailImageButton.setImage(image, for: UIControl.State.normal) }catch{ print("Unable to load image data: \(error)") } } } } //MARK:- delegate method func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { if control == view.rightCalloutAccessoryView { mapView.deselectAnnotation(view.annotation, animated: true) for detail in self.mylocationPins { locationId = detail.locationId providerType = detail.providerType NavigationLink(value: control) { ProfileDetailsView(locationId: $locationId, providerType: $providerType) } break } } } } } } ProfileDetailsView defined like this: @StateObject var manager = LocationManager() @State var tracking:MapUserTrackingMode = .follow @Environment(\.presentationMode) var presentationMode @Binding var locationId: String? @Binding var providerType: String? var body:some View { VStack (alignment: .leading){ Text("Details here...") Button { } label: { Text("Share") .foregroundColor(.blue) } .buttonStyle(.bordered) Button { } label: { Text("Update consumption") .foregroundColor(.blue) } .buttonStyle(.bordered) } } } I get warning: "Accessing State's value outside of being installed on a View. This will result in a constant Binding of the initial value and will not update." inside ProfileMapView line wheer I define @Binding var locationPins: [GpsData.MyEndPt]. That value is being passed into ProfileMapView - so I dont know why then warning. However, ProfileMapView gets called, the mapview is displayed and the marker pin appears and when I click on the disclosure the navigation to other view ProfileDetailsView does not work. I tried NavigationStack and could not make it work because it threw lot of errors. How to fix the code in calloutAccessoryControlTapped method, so I can navigate to other view: ProfileDetailsView. I have spent a week on this trying various things but it hasn't worked.
0
0
551
Mar ’24
SwiftUI WeatherKit returns HTTP status code 403
Trying to get weather data for a specific location and specific timezone. Generated Service identifier and Private Key, from Apple developer site. Then Generated public key Generated jwt token from jwt.io by keying in the payload, header, public, and private key. Header { "alg" : "ES256", // predefined "kid" : “keyid” , // key id created for WeatherKit "id" : “developer_team_account_id.com.company_name.MyWeatherKit, "typ" : "JWT" } Payload { "iat" : 1710117942, "exp" : 1710204342, "iss" : "developer_team_account_id", "sub" : "com.company_name.MyWeatherKit } I Then call this function: func getWeatherData(requestId: String, latitudeStr: String, longitudeStr: String, completion: @escaping (Bool) -> () ){ var country = "US" var language = "en" var tz = "CST" let jwtToken = "token here...." let urlString:String = "https://weatherkit.apple.com/api/v1/availability/" + language + "/" + latitudeStr + "/" + longitudeStr + "?" + "country=" + country + "&" + "timezone=" + tz print("Apple weather urlString: \(urlString)") let weatherURL = URL(string: urlString) var request = URLRequest(url: weatherURL!) request.httpMethod = "GET" request.setValue("Bearer \(jwtToken)", forHTTPHeaderField: "Authorization") let dataTask = URLSession.shared.dataTask(with:weatherURL!) { [self] responseData, response, error in do { print(response as Any) print(error as Any) if let data = responseData { try DispatchQueue.main.sync { [unowned self] in let decoder = JSONDecoder() let jsonData = try decoder.decode(Top.self, from: data) // parse data here print(jsonData) completion(true) } } } catch { print("error: \(error.localizedDescription)") completion(false) } } dataTask.resume() } Gives response with code 403 Optional(<NSHTTPURLResponse: 0x280cbcf00> { URL: https://weatherkit.apple.com/api/v1/availability/en/29.928894042968750/-95.607747517125430?country=US&timezone=CST } { Status Code: 403, Headers { "Access-Control-Allow-Origin" = ( "*" ); Connection = ( close ); "Content-Security-Policy" = ( "default-src 'self';" ); Date = ( "Tue, 12 Mar 2024 02:52:18 GMT" ); Server = ( Apple ); "Strict-Transport-Security" = ( "max-age=31536000; includeSubdomains" ); "X-Cache" = ( "TCP_MISS from a23-38-189-78.deploy.akamaitechnologies.com (AkamaiGHost/11.4.3-54729273) (-)" ); "X-Content-Type-Options" = ( nosniff ); "X-Frame-Options" = ( SAMEORIGIN ); "X-REQUEST-ID" = ( "bac7e5dc-c5fd-6f85-263b-8f59b169cd2f" ); "X-XSS-Protection" = ( "1; mode=block" ); } }) The URL I am passing is : https://weatherkit.apple.com/api/v1/availability/en/29.928894042968750/-95.607747517125430?country=US&timezone=CST Am I calling the wrong URL? Or is Apple weather service down? I am at a loss to understand. I need some help and guidance
0
0
669
Mar ’24
CloudKit is not synchronizing with coredata for relationships
In core-data I have a contact and location entity. I have one-to-many relationship from contact to locations and one-to-one from location to contact. I create contact in a seperate view and save it. Later I create a location, fetch the created contact, and save it while specifying the relationship between location and contact contact and test if it actually did it and it works. viewContext.perform { do { // Set relationship using the generated accessor method currentContact.addToLocations(location) try viewContext.save() print("Saved successfully. Locations count:", currentContact.locations?.count ?? 0) if let locs = currentContact.locations { print("📍 Contact has \(locs.count) locations.") for loc in locs { print("➡️ Location: \(String(describing: (loc as AnyObject).locationName ?? "Unnamed"))") } } } catch { print("Failed to save location: \(error.localizedDescription)") } } In my NSManagedObject class properties I have this : for Contact: @NSManaged public var locations: NSSet? for Location: @NSManaged public var contact: Contact? in my persistenceController I have: for desc in [publicStore, privateStore] { desc.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey) desc.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) desc.setOption(true as NSNumber, forKey: NSMigratePersistentStoresAutomaticallyOption) desc.setOption(true as NSNumber, forKey: NSInferMappingModelAutomaticallyOption) desc.setOption(true as NSNumber, forKey: "CKSyncCoreDataDebug") // Optional: Debug sync // Add these critical options for relationship sync desc.setOption(true as NSNumber, forKey: "NSPersistentStoreCloudKitEnforceRecordExistsKey") desc.setOption(true as NSNumber, forKey: "NSPersistentStoreCloudKitMaintainReferentialIntegrityKey") // Add this specific option to force schema update desc.setOption(true as NSNumber, forKey: "NSPersistentStoreRemoteStoreUseCloudKitSchemaKey") } When synchronization happens on CloudKit side, it creates CKRecords: CD_Contact and CD_Location. However for CD_Location it creates the relationship CD_contact as a string and references the CD_Contact. This I thought should have come as REFERENCE On the CD_Contact there is no CD_locations field at all. I do see the relationships being printed on coredata side but it does not come as REFERENCE on cloudkit. Spent over a day on this. Is this normal, what am I doing wrong here? Can someone advise?
0
0
112
Apr ’25
Push notifications not working, ios 13.6
Upgraded ios 13.6 and changed bundle identifier and container name. Created CKDatabaseSubscription for both public and shared database and can see in cloudkit dashboard. Both didFinishLaunchingWithOptions and didRegisterForRemoteNotificationsWithDeviceToken get called in AppDelegate.   UNUserNotificationCenter.current().delegate = self   UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound], completionHandler: { granted, error in           guard granted else { return }     DispatchQueue.main.async {       application.registerForRemoteNotifications()       print("Registered for Remote notifications")             }   })   return true } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data){   let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }   let token = tokenParts.joined()   print("Device Token: \(token)")   })   self.iCloudSubscribeToPrivateDB()   self.iCloudSubscribeToSharedDB() } In the project both background fetch and remote notifications are enabled. I make databases changes in cloudkit dashboard, but push notifications are not being sent. They were working now just stopped after I made the above changes. What could be wrong?
1
0
1.2k
Jan ’22
Xcode 15.2 project dependencies are not recognized
Loaded both Swift-Collection package 1.1.0 from https://github.com/apple/swift-collections and Facebook 14.1.0 package from https://github.com/facebook/facebook-ios-sdk I open swift file and type import, the prompt shows the module FBSDKCorekit and as soon as select it, it immediately says module not found Does the same thing for OrderedCollection module. Did a clean and then also deleted DerivedData directory contents and rebuilt, same error occurs, does not recognize the modules, even though correct packages exist in Xcode I tied with Faebook 16.3.1 and tried. I deleted the project, created a new project, selected Add Package Dependencies and then deleted the recently sued packages, entered the facebook ios url and tried again. Same error, does not recognize the package contents How can I fix this? Please help.
1
0
698
Feb ’24
NSPersistentCloudKitContainer - Import failed with error: Error Domain=NSCocoaErrorDomain Code=4864
The NSPersistentCloudKitContainer synchronization between core data and iCloud was working fine with phone 15.1. Connected a new iPhone iOS 15.5, it gives error: CoreData: debug: CoreData+CloudKit: -[NSCloudKitMirroringDelegate managedObjectContextSaved:](2504): <NSCloudKitMirroringDelegate: 0x28198c000>: Observed context save: <NSPersistentStoreCoordinator: 0x2809c9420> - <NSManagedObjectContext: 0x2819ad520> 2022-12-05 13:32:28.377000-0600 r2nr[340:6373] [error] error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _importFinishedWithResult:importer:](1245): <PFCloudKitImporter: 0x2837dd740>: Import failed with error: Error Domain=NSCocoaErrorDomain Code=4864 "*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: incomprehensible archive (0x53, 0x6f, 0x6d, 0x65, 0x20, 0x65, 0x78, 0x61)" UserInfo={NSDebugDescription=*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: incomprehensible archive (0x53, 0x6f, 0x6d, 0x65, 0x20, 0x65, 0x78, 0x61)} CoreData: error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _importFinishedWithResult:importer:](1245): <PFCloudKitImporter: 0x2837dd740>: Import failed with error: Error Domain=NSCocoaErrorDomain Code=4864 "*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: incomprehensible archive (0x53, 0x6f, 0x6d, 0x65, 0x20, 0x65, 0x78, 0x61)" UserInfo={NSDebugDescription=*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: incomprehensible archive (0x53, 0x6f, 0x6d, 0x65, 0x20, 0x65, 0x78, 0x61)} I go back and try with my old iPhone iOS 15.1, gives same error.
2
1
1.1k
Aug ’25
CloudKit sharing how to find out the user who shared the CKRecord
If several users are sharing records with .readwrite permission with me, how can I find out who shared which CKRecord? I know user information is confidential information. But I need to be able to find out who shared so I can react to the shared record by either modifying or ignoring. I cannot find anything in Cloud Sharing website by Apple. Can someone give ideas/ponters?
2
0
844
Jan ’23
SwiftUI how to dynamically append a view to an existing view
I have an existing ScrollView view with a Picker. Upon selection of a picker value, and user pressing the details button, I want to append a view to the bottom of the existing view. I call detailsView. But it does not seem to work. @Environment(\.managedObjectContext) private var viewContext @Environment(\.dismiss) var dismiss @Environment(\.presentationMode) var presentationMode @Binding var chosenProvider: Provider? @State var selectedLocation: Location? @State private var vendorNames: [String] = [] @State private var selectedVendor:String? = nil @State private var showingSheet = false @State var state: String? @State var zip: String? var body: some View { ScrollView { VStack { HStack { Text("Select Vendor") Picker("Provider", selection: $selectedVendor , content: { ForEach(vendorNames,id: \.self, content: { name in Text(name) }) }) .pickerStyle(MenuPickerStyle()) .onTapGesture { self.getVendorNames() { providers, status in if (status) { vendorNames = providers } } } } .onChange(of: selectedVendor, perform: { newValue in selectedVendor = newValue }) .tint(.orange) Button { DetailsView() } label: { Label("Details", systemImage: "list.bullet.rectangle") .foregroundColor(.blue) } Spacer() } } .onAppear{ self.getVendorNames() { providers, status in if (status) { vendorNames = providers } } } .navigationTitle("Add Vendor") .toolbar { // Back button ToolbarItem(placement: .navigationBarLeading) { Button(action: { presentationMode.wrappedValue.dismiss() }, label: { HStack(spacing: 2) { Image(systemName: "chevron.backward") .foregroundColor(.black) Button("Back", action: { self.presentationMode.wrappedValue.dismiss() } ) .foregroundColor(.black) } }) } } .navigationViewStyle(StackNavigationViewStyle()) .navigationBarBackButtonHidden(true) } struct DetailsView: View { var body: some View { VStack { Text("Some Details") } } } func getVendorNames (completionHandler: @escaping ([String], Bool) -> Void ) { var names = ["Acme", "Abc"] completionHandler(names, true) } }
2
0
1.9k
Jun ’23