I'm trying some RXSwift code in a playground, and XCode keeps freezing every several minutes with the rainbow spinner. Then XCode stops responding and has to be force quit and restarted. This is happening across multiple projects and Macs. Regular RXSwift code in project files does not cause crashes.
How can I fix XCode freezing when working with RXSwift in playground mode?
import RxSwift
import RxCocoa
import PlaygroundSupport
import Foundation
var str = "Hello, playground"
print(str)
let subject = BehaviorSubject(value: "seed")
let replayed = subject.replay(1)
let sequence = Observable.of("first","Second") //random crashes as I type and the console outputs error messages.
replayed.connect()
replayed.subscribe(onNext: { value in
print(value)
}, onError: { error in
print("Received Error")
}, onCompleted: {
print("Received Completion")
})
Here's my podfile:
platform :ios, '11.0'
use_frameworks!
pod 'RxSwift'
pod 'RxCocoa'
target 'RxSwiftPlayground'
post_install do |installer|
installer.pods_project.build_configurations.each do |config|
config.build_settings.delete('CODE_SIGNING_ALLOWED')
config.build_settings.delete('CODE_SIGNING_REQUIRED')
end
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['CONFIGURATION_BUILD_DIR'] = '$PODS_CONFIGURATION_BUILD_DIR'
end
end
end
I think the only symptom I have is that after force quit, I get this error in console until I rebuild the project (it was compiling and had code completion before the freeze)
Playground execution failed:
error: RxSwift.playground:3:8: error: no such module 'RxSwift'
import RxSwift
Related
I'm trying to transcribe local audio files in my app.
Short files recognised fine, but if audio is more than about 15 min it is not. Console immediately shows this error:
2020-01-17 12:57:07.528986+0300 App[2816:791131] [Utility]
+[AFAggregator logDictationFailedWithError:] Error Domain=kAFAssistantErrorDomain Code=1107 "(null)"
This is my code:
let localRecognitionRequest = SFSpeechURLRecognitionRequest(url: fileUrl)
localRecognitionRequest.shouldReportPartialResults = false
if speechRecognizer.supportsOnDeviceRecognition {
localRecognitionRequest.requiresOnDeviceRecognition = true
}
recognitionTask = speechRecognizer.recognitionTask(with: localRecognitionRequest, delegate: self)
And when there is an error, only one delegate method fires:
func speechRecognitionTask(_ task: SFSpeechRecognitionTask, didFinishSuccessfully successfully: Bool) { }
with successfully = false
I have Xcode 11.3.1
Trying only on device - iPhone XS (iOS 13.3)
Have anyone faced this problem?
I was also seeing error code 1107 and as strange as this sounds, a Simulator reset fixed it for me.
While the simulator is selected:
Go to the top Menu
Select Device
Click on Erase All Content and Settings...
(Optional) Kill XCode and relaunch
This did the trick.
I have integrated in a ios app VimeoNetworking , using the code from the git directly because i cannot integrate using cocoapods (not compatible use of use_frameworks! with other pods) for getting private link to some videos (i have a pro account).
I'm able to authenticate and request video info. When the request is returned and assigned to the class (VIMVideo) the object is not loaded correctly.
If i get the response returned returns correctly a dictionary of 30 items with the video info.
I have checked the same code from the VimeoNetworking example code and it's works in the other project (using same credentials, only different one use pod of Vimeo and the other not)
If i compare the two json responses, both have the same data but in a different order. I have the feeling that the problem is with the de-serialization used by AFNetworking (3.1.0)
Previous authentication
let authenticationController = AuthenticationController(client: VimeoClient.defaultClient, appConfiguration: AppConfiguration.defaultConfiguration, configureSessionManagerBlock: nil)
authenticationController.accessToken(token:tkn) { result in
switch result
{
case .success(let account):
print("authenticated successfully: \(account)")
break;
case .failure(let error):
print("failure authenticating: \(error)")
}
}
Video Request
let requestdir: Request<VIMVideo> = Request<VIMVideo>(path: "/videos/XXXXXXXX")
let _ = VimeoClient.defaultClient.request(requestdir) { [weak self] result in
switch result
{
case .success(let response):
//Here videodir have not value, but
var videodir: VIMVideo! = response.model
case .failure(let error):
let title = "Video Request Failed"
let message = "\(requestdir.path) could not be loaded: \(error.localizedDescription)"
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(action)
strongSelf.present(alert, animated: true, completion: nil)
}
}
Console capture (1)
Pod file from VIMEO EXAMPLE (Extract)
def shared_pods
pod 'AFNetworking', '3.1.0'
pod 'SwiftLint', '0.25.1'
pod 'VimeoNetworking', :path => '../VimeoNetworking'
end
Pod file from my project (Extract)
target 'LibroDig' do
pod 'RestKit', '~> 0.27.3'
pod 'JSONModel'
pod 'SDWebImage', '~>3.8'
pod 'AFNetworking', '3.1.0'
end
I expected the VIMVideo load correctly all the properties. I'm unable to find the difference between the 2 implementations.
Thanks in advance
If everything else is the same, you might be running into issues from opting out of using use_frameworks!.
For example, when I remove this from the Podfile used in the VimeoNetworking example project, I'll see this warning:
The Swift pod VimeoNetworking-iOS depends upon AFNetworking-iOS, which do not define modules. To opt into those targets generating module maps (which is necessary to import them from Swift when building as static libraries), you may set use_modular_headers! globally in your Podfile, or specify :modular_headers => true for particular dependencies.
This article explains the need for use_modular_headers! and mentions interoperability with Objective-C. VimeoNetworking relies on model classes defined in Objective-C, and I wonder if mapping to those models is being affected.
The issue I am having is getting Alamofire to work with the xcode UI Testing.
I have isolated the parts down as much as I can to try and identify where the issue might be, but still can't solve this one. With a new xcode project using swift, I can use Alamofire as expected with the main ViewController.swift and the func viewDidLoad() function okay, but when creating a UI Test, I am unable to use the same code in the func testExample() function.
Versions of tools used:
Xcode = 9.2(9C40b)
Swift = 4.0
cocoapods = 1.4.0
macOS = High Sierra Version 10.13.2 (17C205)
Alamofire = 4.5
ViewController.swift - Working okay
import UIKit
import Alamofire
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Alamofire.request("https://httpbin.org/get").responseJSON { response in
print("Request: \(String(describing: response.request))") // original url request
print("Response: \(String(describing: response.response))") // http url response
print("Result: \(response.result)") // response serialization result
if let json = response.result.value {
print("JSON: \(json)") // serialized json response
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)") // original server data as UTF8 string
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Result
Request: Optional(https://httpbin.org/get)
Response: Optional( { URL: https://httpbin.org/get } { Status Code: 200, Headers {
"Access-Control-Allow-Credentials" = (
true
etc...
UITestExample() - Not Working
//
// exalamUITests.swift
// exalamUITests
//
import XCTest
import Alamofire
class exalamUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
Alamofire.request("https://httpbin.org/get").responseJSON { response in
print("Request: \(String(describing: response.request))") // original url request
print("Response: \(String(describing: response.response))") // http url response
print("Result: \(response.result)") // response serialization result
if let json = response.result.value {
print("JSON: \(json)") // serialized json response
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)") // original server data as UTF8 string
}
}
}
}
Result
2018-01-29 14:55:25.974425+1000 exalamUITests-Runner[12450:454722] +[CATransaction synchronize] called within transaction
2018-01-29 14:55:26.022366+1000 exalamUITests-Runner[12450:454722] Running tests...
2018-01-29 14:55:29.229531+1000 exalamUITests-Runner[12450:454722] Continuing to run tests in the background with task ID 1
Test Suite 'Selected tests' started at 2018-01-29 14:55:29.896
Test Suite 'exalamUITests.xctest' started at 2018-01-29 14:55:29.900
Test Suite 'exalamUITests' started at 2018-01-29 14:55:29.902
Test Case '-[exalamUITests.exalamUITests testExample]' started.
t = 0.00s Start Test at 2018-01-29 14:55:29.908
t = 0.17s Set Up
t = 0.18s Open Company.exalam
t = 0.28s Launch Company.exalam
t = 6.39s Wait for Company.exalam to idle
t = 9.13s Tear Down
Test Case '-[exalamUITests.exalamUITests testExample]' passed (9.339 seconds).
Test Suite 'exalamUITests' passed at 2018-01-29 14:55:39.244.
Executed 1 test, with 0 failures (0 unexpected) in 9.339 (9.342) seconds
Test Suite 'exalamUITests.xctest' passed at 2018-01-29 14:55:39.245.
Executed 1 test, with 0 failures (0 unexpected) in 9.339 (9.346) seconds
Test Suite 'Selected tests' passed at 2018-01-29 14:55:39.249.
Executed 1 test, with 0 failures (0 unexpected) in 9.339 (9.353) seconds
Test session log:
/var/folders/ys/9lh0sqdd62s03g_d10zs46z00000gn/T/com.apple.dt.XCTest/IDETestRunSession-8C0D5A43-AB22-47EA-88C7-6AB878853EBF/ exalamUITests-9DA87773-7D75-4A9A-8127-BAE3CAB18354/Session-exalamUITests-2018-01-29_145508-bLBnaC.log
Podfile
# Uncomment the next line to define a global platform for your project
platform :ios, '9.0'
target 'exalam' do
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!
pod 'Alamofire', '~> 4.5'
# Pods for exalam
target 'exalamTests' do
inherit! :search_paths
# Pods for testing
end
target 'exalamUITests' do
inherit! :search_paths
use_frameworks!
pod 'Alamofire', '~> 4.5'
# Pods for testing
end
end
This Question was similar, but it is over a year old and I thought I could add more detail.
I'm new to Mac, swift, xcode, and cocoapods, but I have tried all similar S.O. related answers already and tried many different things.
(Usually work in python and linux)
Any help would be very much appreciated.
Networking in Alamofire (as all other iOS networking libraries) is asynchronous. Your test is ending well before the request is even processed by the server. That's why your closure for responseJSON method is never fired.
You have to use expectations to get it work:
https://developer.apple.com/documentation/xctest/asynchronous_tests_and_expectations/testing_asynchronous_operations_with_expectations
I'm curious though, why do you need networking inside the UI test?
I am attempting to follow the MetaWear guide on starting a sample application, located here . The problem that I am quickly running into is that I am getting unexpected crashes. Here is how my code is structured
:
Lastly, my Podfile contains the following:
platform :osx, '10.12.6'
target 'meta-wear' do
use_frameworks!
pod 'MetaWear', '~> 2.9'
end
When I run the application, I get a Thread exception as follows on line 5 of the first image:
Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)
While I am certainly a new Swift developer ( noob ), I have no idea why I am unable to reproduce their guide.
Xcode: 9.0
macOS Sierra Version 10.12.6 ( This is where I want to run this command line application )
Update after adding an infinite loop
I updated the main.swift class to ahve the following:
import Foundation
let runLoop = RunLoop.current;
let distantFuture = Date.distantFuture;
print("### we are in the create");
let starter = MetaWearStarter();
print("### we are after the create");
while (runLoop.run(mode: RunLoopMode.defaultRunLoopMode, before: distantFuture)){
print("### listening for a metawear device");
}
I created a class called MetaWearStarter.swift as follows:
import Foundation
import MetaWear
class MetaWearStarter : NSObject {
override init() {
super.init();
print("### we are in the init");
startConnection();
}
func startConnection() {
print("##### connection call was made");
let manager = MBLMetaWearManager.shared();
maanger.startScanForMetaWears() { array in
print("### connection scan was complete")
// Hooray! We found a MetaWear board, so stop scanning for more
MBLMetaWearManager.shared().stopScan()
// Connect to the board we found
if let device = array.first {
device.connectAsync().success() { _ in
print("#### we connected to a device");
}.failure() { error in
print("### unable to connect");
}
}
}
}
}
I get the previous error on this line:
let manager = MBLMetaWearManager.shared();
And my output never makes it past that line:
### we are in the create
### we are in the init
##### connection call was made
An infinite loop to keep the runloop running is not a good habit.
Add a completion handler to your class and stop the runloop on completion.
The usual way to handle the run loop in a CLI is this:
import Foundation
import MetaWear
class MetaWearStarter {
let manager = MBLMetaWearManager.shared()
func startConnection(completion: #escaping (String)->()) {
print("##### connection call was made");
manager.startScanForMetaWears() { array in
print("### connection scan was complete")
// Hooray! We found a MetaWear board, so stop scanning for more
manager.stopScan()
// Connect to the board we found
if let device = array.first {
device.connectAsync().success() { _ in
completion("#### we connected to a device")
}.failure() { error in
completion("### unable to connect, error: \(error.localizedDescription)")
}
} else {
completion("#### no device found")
}
}
}
}
let starter = MetaWearStarter()
let runLoop = RunLoop.current
starter.startConnection { (result) in
print(result)
CFRunLoopStop(runLoop.getCFRunLoop())
}
runLoop.run()
exit(EXIT_SUCCESS)
I have a unit test that succeeds when it is run alone but crashes with an EXC_BAD_ACCESS (most of the time) on waitForExpectations when running alongside other tests.
func testStartMonitoring() {
let mockLocationManager = MockLocationManager()
let beaconListener = BeaconListener(locationManager: mockLocationManager, uuid: BeaconListenerTests.defaultUUID)
let e = self.expectation(description: "Expected beacons to be detected")
//If the listener calls back, the expectation succeeds.
beaconListener.didReceiveNewRoomInformation = { data in
//There are three entries in the test data
XCTAssert(data.count == 3)
e.fulfill()
}
//Start listening
beaconListener.startListening()
//Wait up to 15s for a response
self.waitForExpectations(timeout: 15.0, handler: {error in
if let error = error {
print("\(error)")
}
})
}
I have no other async tests
The test never fails due to exceeded timeout
Since the test only crashes some of the time, I expect that the problem is a race condition somewhere, but I'm unsure where to look.
I've been able to reproduce this with simpler code too:
func testStartMonitoring() {
let e = self.expectation(description: "Expected beacons to be detected")
let deadlineTime = DispatchTime.now() + .seconds(1)
DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
e.fulfill()
}
//Wait up to 15s for a response
self.waitForExpectations(timeout: 15.0, handler: {error in
})
}
I ran the tests from the command line and found this extra piece of information:
Error Domain=IDETestOperationsObserverErrorDomain Code=5 "Early unexpected exit, operation never finished bootstrapping - no restart will be attempted" UserInfo={NSLocalizedDescription=Early unexpected exit, operation never finished bootstrapping - no restart will be attempted}
Some other answers indicate that this may be caused by system alerts. This is understandable, I am using location services which requires a permissions alert. However, the devices on which I'm running the tests already have accepted the permissions and therefore shouldn't be showing the alerts.
I had a similar problem - a set of tests with multiple expectations crashing - and came across your question. It made me realize that its the permissions causing the problem - here for location manager, and speech recognition for me. So I mocked my authorization request class and injected a positive response.
You have to go searching for methods that are calling whatever it is that requires permission - they may or may not be the ones with expectations.