Create and run unit tests, performance tests, and UI tests for your Xcode project using XCTest.

XCTest Documentation

Posts under XCTest tag

182 Posts
Sort by:
Post not yet marked as solved
0 Replies
36 Views
Hi everybody, given the following case using SwiftUI: Button("testButton", action: noop) .accessibilityRepresentation{representation: { Slider(value: $sliderData.sliderValue) }) .accessibilityIdentifier("testSlider") I'm trying to control the slider using XCUITest via slider.adjust(toNormalizedSliderPosition: 0.2) and receive the following error message: Failed: Unable to get expected attributes for slider, found { "XC_kAXXCAttributeMaxScrubberPosition" = { X = 0; Y = 0; }; "XC_kAXXCAttributeMinScrubberPosition" = { X = 0; Y = 0; }; Similarly, print (slider.normalizedSliderPosition) leads to the error message "Failed to determine current position of slider "0 %". Is there a way to set and read the value of accessibilityRepresentation-Sliders with XCUITest? Thanks!
Posted
by
Post not yet marked as solved
1 Replies
112 Views
I have a DataManager class as follows: enum DataManagerType { case normal, preview, testing } class DataManager: NSObject, ObservableObject { static let shared = DataManager(type: .normal) static let preview = DataManager(type: .preview) static let testing = DataManager(type: .testing) @Published var todos = [Todo]() fileprivate var managedObjectContext: NSManagedObjectContext private let todosFRC: NSFetchedResultsController<TodoMO> private init(type: DataManagerType) { switch type { case .normal: let persistentStore = PersistentStore() self.managedObjectContext = persistentStore.context case .preview: let persistentStore = PersistentStore(inMemory: true) self.managedObjectContext = persistentStore.context for i in 0..<10 { let newTodo = TodoMO(context: managedObjectContext) newTodo.title = "Todo \(i)" newTodo.isComplete = false newTodo.date = Date() newTodo.id = UUID() } try? self.managedObjectContext.save() case .testing: let persistentStore = PersistentStore(inMemory: true) self.managedObjectContext = persistentStore.context } let todoFR: NSFetchRequest<TodoMO> = TodoMO.fetchRequest() todoFR.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)] todosFRC = NSFetchedResultsController(fetchRequest: todoFR, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil) super.init() // Initial fetch to populate todos array todosFRC.delegate = self try? todosFRC.performFetch() if let newTodos = todosFRC.fetchedObjects { self.todos = newTodos.map({todo(from: $0)}) } } func saveData() { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch let error as NSError { NSLog("Unresolved error saving context: \(error), \(error.userInfo)") } } } private func fetchFirst<T: NSManagedObject>(_ objectType: T.Type, predicate: NSPredicate?) -> Result<T?, Error> { let request = objectType.fetchRequest() request.predicate = predicate request.fetchLimit = 1 do { let result = try managedObjectContext.fetch(request) as? [T] return .success(result?.first) } catch { return .failure(error) } } } My persistence store is as such: struct PersistentStore { let container: NSPersistentContainer init(inMemory: Bool = false) { container = NSPersistentContainer(name: "CoreDataModel") if inMemory { container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null") } container.viewContext.automaticallyMergesChangesFromParent = true container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } }) } var context: NSManagedObjectContext { container.viewContext } func saveContext () { if context.hasChanges { do { try context.save() } catch let error as NSError { NSLog("Unresolved error saving context: \(error), \(error.userInfo)") } } } } I get an error when calling: let predicate = NSPredicate(format: "id = %@", todo.id as CVarArg) //todo.id is just some UUID() //irrelevant here let result = fetchFirst(TodoMO.self, predicate: predicate) This is the error: 2022-07-09 21:36:17.425709-0400 CoreDataExample[73965:7495035] [error] error: No NSEntityDescriptions in any model claim the NSManagedObject subclass 'CoreDataExampleTests.TodoMO' so +entity is confused. Have you loaded your NSManagedObjectModel yet ? CoreData: error: No NSEntityDescriptions in any model claim the NSManagedObject subclass 'CoreDataExampleTests.TodoMO' so +entity is confused. Have you loaded your NSManagedObjectModel yet ? 2022-07-09 21:36:17.425780-0400 CoreDataExample[73965:7495035] [error] error: +[CoreDataExampleTests.TodoMO entity] Failed to find a unique match for an NSEntityDescription to a managed object subclass CoreData: error: +[CoreDataExampleTests.TodoMO entity] Failed to find a unique match for an NSEntityDescription to a managed object subclass /Users/santiagogarciasantos/Documents/Xcode Projects/CoreDataExample/CoreDataExample/DataManager/DataManager.swift:87: error: -[CoreDataExampleTests.CoreDataExampleTests test_Add_Todo] : executeFetchRequest:error: A fetch request must have an entity. (NSInvalidArgumentException) I've checked the target, made sure my Entity is in "Current Product Module" but it still won't work. Important: This only occurs when I'm testing (using my DataManager.testing)
Posted
by
Post not yet marked as solved
0 Replies
60 Views
I've got a UIAutomation test that tests an app with a Share Extension. I want to pass in some launchArguments and launchEnvironment properties to the Share Extension in my test. I can't figure out a way of doing it. When debug the ProcessInfo in the extension my values aren't there. I've tried setting them like this: XCUIApplication(bundleIdentifier:"com.my.app").launchArguments = ["TEST"] XCUIApplication(bundleIdentifier:"com.my.app").launchEnvironment = ["TEST":"TEST"] and this: XCUIApplication().launchArguments = ["TEST"] XCUIApplication().launchEnvironment = ["TEST":"TEST"] Note, I am correctly getting the correct process when I'm finding it with the bundle identifier.
Posted
by
Post not yet marked as solved
0 Replies
89 Views
For the Core Data stack in my project's test target, I have the NSPersistentStoreDescription's url set to "/dev/null" as recommended by Apple at WWDC18. I previously was using an in-memory persistent store. I have found that tests that test fetches where the fetch request is set to have the result type as NSFetchRequestResultType.dictionaryResultType will always fail. However, when running the project, the very same code will work as expected. Is there really no way to test these fetches? I have found nothing from search engines. I understand that a persistent store is required for this result type but is "/dev/null" not supposed to give us the same behaviour?
Posted
by
Post not yet marked as solved
0 Replies
106 Views
Getting error in XCUIApplication.launch() after deleting app between tests using Springboard. I created about 20 UI tests in a few different files. Every time a test ends I delete the app from the device using Springboard in the tear down func. When I execute one test at the time everything works fine and without any problems. But when I execute the whole testplan or all tests from one file I always get an error after the first time as soon as I try to launch the second test.  This is the error I receive every time: Failed to create directory on device 'iPhone' (device identifier) to hold runtime profiles for application with bundle ID ‚bundle ID': No matching application with bundle identifier ‚bundle ID' Domain: IDEFoundationErrorDomain Code: 17 User Info: {     DVTErrorCreationDateKey = "2022-06-30 11:42:41 +0000";     IDERunOperationFailingWorker = IDELaunchiPhoneLauncher; } My Springboard class looks like this  Setup looks like this  Tear down looks like this  The error always occurs in the setUpWithError func on line app.launch(). Does anyone know how to solve this problem?  Thanks in advance for any help or answers. best regards Stefan
Posted
by
Post not yet marked as solved
1 Replies
138 Views
Hello, I am automating a test scenario, as part of it I have to make a Raspberry Host connection which is on local area network. I can make successful connection to the host from UnitTest target. But the connection is failing when I make the same connection from Unit Test target. I am using XCUITest to automate the app. I am blocked here. I did refer some posts but didn't find any solution. Kindly help. Thanks, Sudheer
Post not yet marked as solved
0 Replies
97 Views
I have an app that relies on Core Data for persistence. The app is using MVVM architecture in order to facilitate testing The dev environment is a MacBook Pro (M1 Max) running MacOS 12.4 and Xcode 14 beta 2 So far everything has been working well until I attempted to add a new entity to my Model that had a relationship (many-to-one) to another entity. Attempting to instantiate one of these entities resulted in a NSUnknownKeyException associated with the property that defined the relationship so I deleted this relationship from the model and re-ran the test. Much to my surprise, the error persisted and I have been singularly unable to resolve it since despite the following: Delete derived data, reboot XCode Rename offending entity (error persists, just with the different entity name) Delete entity and add back into the Model Turn off code-gen and defined the MO subclass manually Check Core Data XML - this looks unremarkable and there are no residual properties that could be causing the problem The one thing I haven't tried yet is to run the code through Xcode 13 (it's a new machine so I was all enthusiastic and went straight for the beta which might have been a mistake!) so will be doing that shortly. For now it seems that something relating to the Core Data model and relationships between entities is hiding out somewhere I can't find it but it could be a bug in the tooling. The problem of course is that I can't continue to develop the app with a compiler error I can't clear. Any thoughts or guidance would be very welcome... Xcode Model interface for relevant entities and XML: Extension on the offending ManagedObject subclass (convenience methods): extension Prescription {     // MARK: - INTERNAL TYPES     enum PointOfCareContext: String, CustomStringConvertible {         case premedication, perioperative, postoperative, hospitalised         var description: String {             return self.rawValue.capitalized         }     }     // MARK: - PROPERTIES     var drug: Drug {         get { guard let drug = cd_drug else {             fatalError("Persistent store corrupted: Prescription is missing relationship to Drug.")         }             return drug         }         set { cd_drug = newValue }     }          var timePrescribed: Date {         get { guard let timePrescribed = cd_timePrescribed else {             fatalError("Persistent store corrupted: Prescription is missing timePrescribed.")         }             return timePrescribed         }         set { cd_timePrescribed = newValue }     }     /// When the drug should be administered     /// Passing nil to this property indicates the drug should be given asap (so will return current Date)     var timeScheduled: Date? {         get { guard let timeScheduled = cd_timeScheduled else {             return Date.now         }             return timeScheduled         }         set { cd_timeScheduled = newValue }     }     /// When the drug was administered     /// Nil indicates not given yet     var timeAdministered: Date? {         get { return cd_timeAdministered }         set { cd_timeScheduled = newValue }     }     var doseRate: Measurement<UnitDensity> {         get {             if (cd_doseRate != 0) {                 fatalError("Persistent store corrupted: Prescription doseRate == 0.")             }             return Measurement(value: cd_doseRate, unit: .milligramsPerKilogram)         }         set {             cd_doseRate = newValue.converted(to: .milligramsPerKilogram).value         }     }     var dose: Measurement<UnitMass> {         get {             return Measurement(value: cd_dose, unit: .milligrams)         }         set {             cd_doseRate = newValue.converted(to: .milligrams).value         }     }     var doseVolume: Measurement<UnitVolume> {         get {             return Measurement(value: cd_doseVolume, unit: .milliliters)         }         set {             cd_doseVolume = newValue.converted(to: .milliliters).value         }     }     var context: PointOfCareContext {         get {             guard let contextValue = cd_context, let context = PointOfCareContext(rawValue: contextValue) else {                 fatalError("Persistent store corrupted: Prescription has an invalid administration context [\(cd_context ?? "")]")             }             return context         }         set {             cd_context = newValue.rawValue         }     } Error encountered when attempting to save managed object context in the unit test:
Posted
by
Post not yet marked as solved
0 Replies
115 Views
Hello, We have multiple iOS real devices attached to a Mac mini which serve as a server in a CI pipeline. From iOS 15 after a few hours, the phone requires the pin code, even if the UI automation is enabled and the pin was set at the first run. A few mentions: We need to have a pin set because the app under test needs a pin for security reasons We set the display to never sleep because we cannot unlock the phone through the automation script For automation, we're using Appium (https://github.com/appium/appium) My question is, how can we handle the case without unlocking manual the phone considering that we're using the devices in a CI pipeline?
Posted
by
Post not yet marked as solved
0 Replies
113 Views
I am running my UI Tests on Github CI and the tests are flaky. I don't understand how I can fix it. The animations are disabled and I am running the tests on a iPhone 13 plus. A lot of tests are running green, but some are not working. Locally, I got everything working. These are some logs: 2022-06-21T13:42:23.2627250Z t = 63.34s Tap Cell 2022-06-21T13:42:23.2707530Z t = 63.34s Wait for com.project.project to idle 2022-06-21T13:42:23.2733620Z t = 63.41s Unable to monitor event loop 2022-06-21T13:42:23.2734250Z t = 63.41s Unable to monitor animations 2022-06-21T13:42:23.2734800Z t = 63.42s Find the Cell 2022-06-21T13:42:24.1158670Z t = 64.45s Find the Cell (retry 1) 2022-06-21T13:42:24.1287900Z t = 64.45s Collecting extra data to assist test failure triage 2022-06-21T13:42:24.2022460Z /Users/runner/work/project/UITestCase.swift:665: error: -[project.UserTagTest testTapInTextView] : Failed to get matching snapshot: Lost connection to the application (pid 12676). (Underlying Error: Couldn’t communicate with a helper application. Try your operation again. If that fails, quit and relaunch the application and try again. The connection to service created from an endpoint was invalidated: failed to check-in, peer may have been unloaded: mach_error=10000003.) It can not find the cell because of these logs: Unable to monitor event loop Unable to monitor animations I know this because I sometimes get different errors than the error above, which says that the connection to the application is lost, right below the Unable to monitor... error logging. Is there anything I can try? I don't have a reproduction project. This is the command that is executed: xcodebuild test -project project.xcodeproj -scheme project-iosUITests -destination 'platform=iOS Simulator,name=iPhone 13 Pro,OS=15.5' The CI runs 35 tests and 5 fails randomly with the Unable to errors. Is there any suggestion to fix this problem?
Posted
by
Post not yet marked as solved
2 Replies
169 Views
I have configured multiple test plans, I see them in the scheme editor. I have marked one as default. Now I would like to choose a specific one for the Xcode Cloud Test action, but there is only the option "Use Scheme Settings". The Test Action in the workflow The Test Plans in the Scheme
Posted
by
Post marked as solved
1 Replies
129 Views
Hello, we use XCTest to run test on our macOS apps. It is good, but it prevents the use of the mac in the meantime, since it actually moves the mouse and perform click, rather than simulate them. Is there a way to send mouse movements and clicks to the app, rather than actually moving the mouse? Can I run the test inside a macOS simulator? How do XCTest work under the hood? I can see the testing framework has access to a very detailed view of what's inside the macOS app, even though we have not done anything special. Is it using something like Apple Script under the hood?
Posted
by
Post not yet marked as solved
0 Replies
127 Views
Even when you separate business logic code from your SwiftUI views the previews and also view bodies seems both to count for the unit test code coverage. I read many articles in the internet about how to test SwiftUI code and archive good code coverage. But they all seem not to be the perfect solution for this task. Is there any good guide for unit and ui testing SwiftUI code that Apple recommends for their apps?
Posted
by
Post not yet marked as solved
1 Replies
247 Views
Hi, I'm currently researching if we are able to migrate to Xcode Cloud in our project. I encountered one issue. I run unit tests on Xcode Cloud and I see that they finish in ~150 seconds, but the whole step takes ~530s and there is no information in logs why. I even run the same command on my local computer and it doesn't take that long. Any ideas? Any way to optimize it? Also one more thing: it looks like Xcode Cloud is not running on M1 machines. Do you know guys if there are plans for Xcode Cloud to take advantage of M1/M2?
Posted
by
Post not yet marked as solved
0 Replies
130 Views
Are there commands for testing watch complications in XCUITest? So far I see that we can press the home button and rotate the Digital Crown in test As of Xcode Version 14.0 beta (14A5228q) the XCUITest record function doesn't work. Can't find anything in debugDescription to helpout either with reaching complications https://developer.apple.com/documentation/xctest/xcuidevice/button
Posted
by
Post not yet marked as solved
4 Replies
299 Views
When I generate an xctestrun file using Xcode 14 with: xcodebuild build-for-testing -project UITestTesting.xcodeproj -scheme UITestTesting -destination 'id=00008020-000545362EE1002E' -derivedDataPath ./build I'm able to see the xctestrun file at "/Users/noahmartin/Desktop/UITestTesting/Build/Build/Products/UITestTesting_iphoneos16.0-arm64.xctestrun" However, I can't use it to run tests on my iOS 16 iPad. I'm trying to invoke the test like this: xcodebuild test-without-building -xctestrun "/Users/noahmartin/Desktop/UITestTesting/Build/Build/Products/UITestTesting_iphoneos16.0-arm64.xctestrun " -destination 'id=00008020-000545362EE1002E' -derivedDataPath ./build And getting this error: xcodebuild: error: Unable to find a destination matching the provided destination specifier: { id:00008020-000545362EE1002E } Available destinations for the "Transient Testing" scheme: { platform:macOS, arch:arm64e, id:00006001-0012198A0102801E } { platform:macOS, arch:arm64, id:00006001-0012198A0102801E } { platform:macOS, arch:x86_64, id:00006001-0012198A0102801E } { platform:macOS, arch:arm64e, variant:Mac Catalyst, id:00006001-0012198A0102801E } { platform:macOS, arch:arm64, variant:Mac Catalyst, id:00006001-0012198A0102801E } { platform:macOS, arch:x86_64, variant:Mac Catalyst, id:00006001-0012198A0102801E } { platform:macOS, arch:arm64e, variant:DriverKit, id:00006001-0012198A0102801E } { platform:macOS, arch:arm64, variant:DriverKit, id:00006001-0012198A0102801E } { platform:macOS, arch:arm64, variant:Designed for [iPad,iPhone], id:00006001-0012198A0102801E } { platform:iOS Simulator, id:3113F5B7-7358-4ADE-9660-667872D113A7, OS:16.0, name:iPad (9th generation) } { platform:iOS Simulator, id:D7232872-AC19-4DF1-BF18-D23C2C2A5BFE, OS:16.0, name:iPad Air (5th generation) } { platform:iOS Simulator, id:EE6444F9-2664-4907-9481-08CE44D028E9, OS:16.0, name:iPad Pro (9.7-inch) } { platform:iOS Simulator, id:10063708-10B3-4510-A41F-E948B2D09DB3, OS:16.0, name:iPad Pro (11-inch) (3rd generation) } { platform:iOS Simulator, id:794714E1-25E0-474A-BA79-F5E0EFA3E646, OS:16.0, name:iPad Pro (12.9-inch) (5th generation) } { platform:iOS Simulator, id:809FAD25-CFE5-44CA-B642-0FF2A0E638E5, OS:16.0, name:iPad mini (6th generation) } { platform:iOS Simulator, id:055D580A-859B-42F8-B306-BD8CB68BF1CC, OS:16.0, name:iPhone 8 } { platform:iOS Simulator, id:228440FE-9536-401D-9221-E909761468FE, OS:16.0, name:iPhone 8 Plus } { platform:iOS Simulator, id:D2F30B3E-32F9-44B2-9B02-20A1B6FEDFC3, OS:16.0, name:iPhone 11 } { platform:iOS Simulator, id:1677A963-4BBC-4DE3-896B-2D93FBF10A1B, OS:16.0, name:iPhone 11 Pro } { platform:iOS Simulator, id:67F569A4-B422-406F-961A-C9093F4EA861, OS:16.0, name:iPhone 11 Pro Max } { platform:iOS Simulator, id:927F62C4-CB4E-487A-B021-0A986B9B700A, OS:16.0, name:iPhone 12 } { platform:iOS Simulator, id:AAAE026B-A40E-4D84-9447-91B2034B6FDA, OS:16.0, name:iPhone 12 Pro } { platform:iOS Simulator, id:96E6D2AB-140B-496F-8C31-71A12412AB0C, OS:16.0, name:iPhone 12 Pro Max } { platform:iOS Simulator, id:B68ACAB0-A87A-4384-B9F8-63ECF09D9564, OS:16.0, name:iPhone 12 mini } { platform:iOS Simulator, id:E6FFBA89-6B9E-4A76-A99E-0510E1EFE97B, OS:16.0, name:iPhone 13 } { platform:iOS Simulator, id:0ECA5023-8C7B-4CFA-B264-E0539509E61A, OS:16.0, name:iPhone 13 Pro } { platform:iOS Simulator, id:203AC07C-503F-476E-9F14-DA7FA4D63131, OS:16.0, name:iPhone 13 Pro Max } { platform:iOS Simulator, id:16AA1AE3-1D75-4358-A4FB-8A73141A0551, OS:16.0, name:iPhone 13 mini } { platform:iOS Simulator, id:FAC28F61-2CF8-40C1-AB2D-64CE6F11B96B, OS:16.0, name:iPhone SE (3rd generation) } Ineligible destinations for the "Transient Testing" scheme: { platform:iOS, id:dvtdevice-DVTiPhonePlaceholder-iphoneos:placeholder, name:Any iOS Device } { platform:iOS Simulator, id:dvtdevice-DVTiOSDeviceSimulatorPlaceholder-iphonesimulator:placeholder, name:Any iOS Simulator Device } { platform:macOS, name:Any Mac } { platform:macOS, variant:Mac Catalyst, name:Any Mac } { platform:tvOS, id:dvtdevice-DVTiOSDevicePlaceholder-appletvos:placeholder, name:Any tvOS Device } { platform:tvOS Simulator, id:dvtdevice-DVTiOSDeviceSimulatorPlaceholder-appletvsimulator:placeholder, name:Any tvOS Simulator Device } { platform:watchOS, id:dvtdevice-DVTiOSDevicePlaceholder-watchos:placeholder, name:Any watchOS Device } { platform:watchOS Simulator, id:dvtdevice-DVTiOSDeviceSimulatorPlaceholder-watchsimulator:placeholder, name:Any watchOS Simulator Device } I am able to launch the test directly from xcode, or with the "project" and "scheme" flags and xcodebuild test but I can't get the xctestrun file to work with iOS 16. This method works fine for iOS 15/Xcode 13. Is there anything I'm missing to make this work with the new betas? Also filed as FB10129497
Posted
by
Post not yet marked as solved
0 Replies
155 Views
I want to test app launch performance in my project. Therefore I tried to use performance test with measure func and XCTApplicationLaunchMetric. But after test completion there is no any result with average time. Here is a test example: func testLaunchPerformance() throws {         if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) {             // This measures how long it takes to launch your application.             measure(metrics: [XCTApplicationLaunchMetric()]) {                 XCUIApplication().launch()             }         }     } But when I create a new empty project and add the same performance test – it works and shows app launch results. 1st image is a real project test – there is no test result. and the 2nd image is a demo empty project test – it has performance result diagram. I am running test on MacBook with M1 Pro chip. However, when my colleague is running the same performance test on our real project with Intel based MacBook Pro – all is fine, it shows app launch results correctly as my demo project. I have no idea how it can be fixed, because it seems that it depends on M1 chip 🤷🏻‍♂️. May be somebody have a solution?
Posted
by
Post not yet marked as solved
0 Replies
157 Views
I updated my machine to: macOS Monterey Version 12.4 Xcode Version 13.4 (13F17a) iOS Version 15.4.1 (19E258) device real (iPhone 11) iOS Version 15.5 (19F77) device real (iPhone 11) I executed this command on host machine which is wirelessly connected to X code. $ automationmodetool enable-automationmode-without-authentication Setting up machine to allow Automation Mode without requiring user authentication... succeeded. $ automationmodetool Automation Mode is disabled. This device DOES NOT REQUIRE user authentication to enable Automation Mode. but I still get this exception Underlying Error: Timed out while enabling automation mode. My devices constantly requests password to enable UI Automation.
Posted
by
Post not yet marked as solved
0 Replies
161 Views
Hi All, I want to learn and write unit test cases using Mock class and stubs for MVVM design implementation. Also I want to test API calls using XCTestCase framweork. I need recommended guidelines or way for writing test cases for following class designs. I am facing problem for how to test code/data from mock class with actual class code. Thanks in Advance for valuable help. Please ignore hardcoded error values. //NetworkManager.swift protocol GetAPIRquestData { var path: String { get set } var method: String { get set } func getAPIData(_ completion: @escaping (Result<Data, Error>) -> Void) -> Void } class NetworkManager: GetAPIRquestData { var path: String var method: String private let session: URLSession init(session: URLSession = URLSession(configuration: .default), path: String, method: String) { self.session = session self.path = path self.method = method } func getAPIData(_ completion: @escaping (Result<Data, Error>) -> Void) -> Void { guard let request = try? buildRequest() else { return } let task = session.dataTask(with: request) { data, response, error in if let data = data { if let response = response as? HTTPURLResponse, response.statusCode == 200 { completion(.success(data)) } else { completion(.failure(NSError(domain: "Invalid data", code: 205, userInfo: nil))) } } else { completion(.failure(NSError(domain: "Data error", code: 400, userInfo: nil))) } } task.resume() } func buildRequest() throws -> URLRequest { // Construct a URL by assigning its parts to a URLComponents value var components = URLComponents() components.scheme = "https" components.host = "api.developer.com" components.path = self.path // This will give us the constructed URL as an optional guard let url = components.url else { throw NSError(domain: "Invalid URL", code: 10, userInfo: nil) } var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 10) request.httpMethod = self.method return request } } //HomeUsersViewModel.swift struct UsersViewModel { let loginUserName: String? let avatarUrl: String? init(userModel: HomeUsersModelElement) { self.loginUserName = userModel.login self.avatarUrl = userModel.avatarURL } } protocol ParsableData { var arrayUsersViewModel: [UsersViewModel] { get set } var output: OutputHomeViewData? { get set } func getParsableData() -> Void } protocol OutputHomeViewData: AnyObject { func didReceivedOutPutData(_ userViewModel: [UsersViewModel]?, error: Error?) -> Void } final class HomeUsersViewModel: ParsableData { weak var output: OutputHomeViewData? var arrayUsersViewModel: [UsersViewModel] = [] private let getApiData: GetAPIRquestData init(getApiData: GetAPIRquestData){ self.getApiData = getApiData } func getParsableData() -> Void { getApiData.getAPIData { result in switch result { case .success(let data): do { let jsonData = try JSONDecoder().decode(HomeUsersModel.self, from: data) let viewModel = self.mapModelDataToViewModelData(userModel: jsonData) self.output?.didReceivedOutPutData(viewModel, error: nil) } catch let error { self.output?.didReceivedOutPutData(nil, error: error) } case .failure(let err): self.output?.didReceivedOutPutData(nil, error: err) } } } //Map API response data to View Model and assign to delegete object. func mapModelDataToViewModelData(userModel: HomeUsersModel) -> [UsersViewModel] { let modelArray = userModel.map { (obj: HomeUsersModelElement) -> UsersViewModel in return UsersViewModel(userModel: obj) } return modelArray } } //HomeUsersViewController.swift class HomeUsersViewController: UIViewController {    private var parsableData: ParsableData = HomeUsersViewModel(getApiData: NetworkManager(session: URLSession(configuration: .default), path: "/users", method: "GET"))   private var userVM: [UsersViewModel] = []   override func viewDidLoad() {     super.viewDidLoad()          parsableData.getParsableData()     parsableData.output = self   } } extension HomeUsersViewController: OutputHomeViewData {       func didReceivedOutPutData(_ userViewModel: [UsersViewModel]?, error: Error?) {     if let userVM = userViewModel {       self.userVM = userVM       print("VM:\(self.userVM)")     } else if let _ = error {             } else {       }   } }
Posted
by
Post not yet marked as solved
1 Replies
165 Views
Hey people, I recently switched to a macbook pro M1 from an intel one, and I'm not able to run unit tests on the M1, it builds, but as soon as it runs it just pauses as you can see in the screenshot and if I try to continue the execution it just keeps stopping there. I also tried creating a new test target on the M1 laptop but when I execute it the same things happens. backtrace:  * frame #0: 0x0000000204a6145e dyld`__shared_region_check_np + 10   frame #1: 0x0000000204a3b2e4 dyld`dyld3::reuseExistingCache(dyld3::SharedCacheOptions const&, dyld3::SharedCacheLoadInfo*) + 30   frame #2: 0x0000000204a3b241 dyld`dyld3::loadDyldCache(dyld3::SharedCacheOptions const&, dyld3::SharedCacheLoadInfo*) + 1857   frame #3: 0x0000000204a39156 dyld`dyld4::SyscallDelegate::getDyldCache(dyld3::SharedCacheOptions const&, dyld3::SharedCacheLoadInfo&) const + 58   frame #4: 0x0000000204a2325f dyld`dyld4::ProcessConfig::DyldCache::DyldCache(dyld4::ProcessConfig::Process&, dyld4::ProcessConfig::Security const&, dyld4::ProcessConfig::Logging const&, dyld4::SyscallDelegate&) + 469   frame #5: 0x0000000204a22481 dyld`dyld4::ProcessConfig::ProcessConfig(dyld4::KernelArgs const*, dyld4::SyscallDelegate&) + 105   frame #6: 0x0000000204a20486 dyld`start + 310
Posted
by