UIPasteboard.general.string takes too long - ios

In my UI test, I have a test where I am using the UIPasteboard to throw the input around. Just before I use it, I store the current value of the pasteboard into a local temporary variable like so: let currentClipboard = UIPasteboard.general.string ?? "" and it will be restored again at the end of the test like so: UIPasteboard.general.string = currentClipboard. However, sometimes the let currentClipboard = UIPasteboard.general.string ?? "" line takes forever to complete, if at all. I've waited like 1-2 minutes and it still stuck there. I know this because I actually added a breakpoint right below that line and it was never called. Can anybody tell me what's wrong with my code? Thanks.

I've faced the same issue in the simulator only.
If you're testing in simulator then just reset the simulator and it'll start working fine. And I didn't find this type of issue in the real device.

Related

why my print result of from one swift file does not appear in xcode debug area

xcode debug area
hi,
i am a new beginner in iOS development. i am trying to learn someone code to build an app.
here is the screenshot of my problem : https://i.stack.imgur.com/4QX5P.png
i am trying to print("helloo") and print("your requestID is : ") but it doesnt appear in my debug area, that code is written in my ViewController.swift file
the debug area just print out the networking result from VenuesTableViewController.swift file (from another swift file)
what went wrong in here ? thanks in advance :)
Based on your code, it's very strange that your printing "helloo" doesn't appear on your debug area since it is declared on the viewDidLoad of your ViewController. Did you really use this ViewController ?
The second print "Your request id..." can or not be print based on your previous guard statements : guard let dictionnarayJSON...guard let meta...guard let requestID. A guard statement allows you to control the flow of your code. If what you test is correct it can continue to proceed your code. If not you put return so the flow of your code is stopped.
So, if one of your 3 guard statements fails, you can't reach your printing statement print(Your requet id...)
I recommend you to see Apple documentation : Control Flow

iOS Firebase - Crash in simulator but not device w/ persistence

I tried googling this problem but it seems like everyone has the opposite problem where the app runs on simulator but not their device. I've been struggling a LOT all week with firebase asynchronous calls returning null and linked the issue to persistence being enabled. All my problems go away if I disable persistence, but I want it enabled. I learned recently about synchronous issues with the different listeners/persistence and have been struggling with firebase returning outdated/nil values for a while.
Simulator was working just a week or two ago and I'm not sure what's changed. I've tried messing with / switching out .observeSingleEvent for .observe and still crashes at this code:
let synced = ref.child("profiles").child((FIRAuth.auth()?.currentUser?.uid)!).child("level")
synced.observeSingleEvent(of: FIRDataEventType.value, with: { (snapshot) in
print(snapshot)
print(snapshot.ref)
if (snapshot.value as! String == "One") {
........//CRASH
With the message:
Could not cast value of type 'NSNull' (0x10b7cf8c8) to 'NSString' (0x10a9dfc40).
When I try to print snapshot, it shows me an empty snapshot. But when I print the ref, the link works and takes me to the right place in my db (where I can see the data exists)
Any ideas how to fix/get around this without disabling persistence? Or more importantly I guess, should I care that it doesn't work in simulator if it works on a device? Will this matter for app store approval / affect future users?
If you'd like to see for yourself that this is an issue of firebase getting a nil/outdated value when the reference exists, here is what I see when I follow the printed ref link
The error seems fairly explicit: there is no value, so you can't convert it to a string.
synced.observeSingleEvent(of: FIRDataEventType.value, with: { (snapshot) in
if (snapshot.exists()) {
if (snapshot.value as! String == "One") {
........//CRASH

Can not access the programatically added UIView in XCTest

Below is my recorded XCTest
let app = XCUIApplication()
let tablesQuery = app.tables
tablesQuery.staticTexts["Video"].tap()
tablesQuery.staticTexts["\tWindowed"].tap()
app.buttons["Launch"].tap()
app.buttons["Popout Video"].tap()
app.children(matching: .window).element(boundBy: 0).children(matching: .other).element(boundBy: 1).tap()
When I am trying to run the test the last part that is:
app.children(matching: .window).element(boundBy: 0).children(matching: .other).element(boundBy: 1).tap()
is not accessible. It does not throw any error but the last line of code is not executed.
I have tried solving the issue by referring to the following stackoverflow question :
Xcode UI Tests can't find views that are added programatically
Also , I have referred to the following Apple Documentations: https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/iPhoneAccessibility/Making_Application_Accessible/Making_Application_Accessible.html#//apple_ref/doc/uid/TP40008785-CH102-SW2
https://developer.apple.com/reference/uikit/uiview
But all these doesn't seem to solve the issue. Any help will be greatly appreciated.
The line in question is very brittle. It's possible that your app's views are not always available in the same order every time the app launches, depending on race conditions, so what was recorded in your recording session does not necessarily work for all launches of the app. You'll probably find that the code is actually running, but isn't tapping the element you expected.
To make your code less brittle, add an accessibility identifier to the UIView in your app code, and use the otherElements query to find the UIView.
// app code
let view: UIView!
view.accessibilityIdentifier = "myAccessibilityIdentifier"
// UI test code
app.otherElements["myAccessibilityIdentifier"].tap()

Using reopened standard file descriptors in an iOS app with background capabilities?

I would like to be able to redirect my logging statements to a file so that I can retrieve them when my app runs standalone (i.e. is not attached to Xcode). I have discovered (thank you Stackoverflow) that freopen can be used to accomplish this.
If I create a new Xcode project and add the code to redirect stderr then everything works as expected.
However, when I add the redirection code to my existing, bluetooth project I am having trouble. The file is being created and I can retrieve it using iTunes or Xcode's Devices window, but it is of size 0. If I explicitly close the file then the text that I wrote actually makes it into the file. It is as though iOS is not flushing the file when the app is terminated. I suspect that the trouble stems from the fact that I have enabled background processing. Can anyone help me to understand this?
Here is my code:
let pathes = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true);
let filePath = NSURL(fileURLWithPath: pathes[0]).URLByAppendingPathComponent("Test.log")
freopen(filePath.path!, "a", stderr);
fputs("Hello, Samantha!\r\n", stderr);
struct StderrOutputStream: OutputStreamType {
static let stream = StderrOutputStream()
func write(string: String) {fputs(string, stderr)}
}
var errStream = StderrOutputStream.stream
print("Hello, Robert", toStream: &errStream)
fclose(stderr) // Without this the text does not make it into the file.
I'd leave this as a comment, but have you looked into NSFileHandle? It sounds like you just need a way to append data to the end of a text file, correct?
Once you have a handle with something like NSFileHandle(forWritingToURL:), you can use .seekToEndOfFile() and .writeData(_:). As a side note, you'll need to convert your String to Data before writing it.
Admittedly, this will probably end up being more lines of code, and you'll almost certainly need to take threading into consideration.

iOS AddressBook Swift BadAccess

So here's the deal:
I am building an app that accesses the internal addressbook on the iPhone. Everything was working fine (and is working fine on the simulator still), but now on the device I get a ThreadBreak and lldb opens up with no error message in the console on this line:
tempPerson.firstname = ABRecordCopyValue(person, kABPersonFirstNameProperty)?.takeRetainedValue() as String? ?? ""
Again, this is still working on the simulator mind you and used to work just fine.
There is some multithread action going on because I am loading the addressbook into memory in the background using GCD above:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
My addressbook was loaded properly. I have deleted the app from my test device (iPhone 6), cleaned the project (figuring it could be a bad link between some Obj-C bridge file that didn't like the ABAddressBook datatype, and even hopped on one foot while holding the phone Northward for good luck. Nothing worked.
I just can't figure out why it would work on all the Simulators and not on the phone. I do, however, notice that the app is not asking permission to access the contacts when it firsts opens after deleting (though the Authorization check is called and is granting authorization):
case .Authorized:
return self.createAddressBook()
I'm at a loss at even what to show you all since it's not returning much of anything, but here is a breakdown of the Thread Error (NOTE: Sometimes it happens on different threads...)
Thread 4
Queue: com.apple.root.background.-qos (concurrent)
0 swift_getObjectType
1 swift_dynamicCast
2 SomeApp.ViewController.(createAddressBook(SomeApp.ViewController) -> () -> Swift.Bool).(closure #1)
3_Dispatch_call_block_and_release
4_dispatch_client_callout
5_dispatch_root_queue_drain
6_dispatch_worker_thread3
7_pthread_wqthread
Enqueued from com.apple.main-thread (Thread 1)
0_dispatch_async_f_slow
*>> 1_SomeApp.ViewController.createAddressBook(SomeApp.ViewController)() -> Swift.Bool [inlined]
2_SomeApp.ViewController.determineStatus(SomeApp.ViewController)() -> Swift.Bool
3_SomeApp.ViewController.loadContacts(SomeApp.ViewController() -> ()
4_SomeApp.ViewController.viewDidLoad(SomeApp.ViewController() -> ()
... etc Viewloading stuff
On the breakpoint, the two variables given in the debugger are
The addressbookref
adbk = (AnyObject?) (instance_type = Builtin.RawPointer = 0x... EvaluatingTo: Some
and the ViewController called "Self"
self(SomeApp.ViewController)
containing all the variables my app uses elsewhere.
Sorry for being so verbose, but I really don't know what of this is relevant and what isn't..
Thanks for your help in advance!
Update: I turned off multithreading/ dispatching and it didn't work. So it must be something to do with that tempPerson.firstname bit.
Update 2: It does go around the loop twice and get two contacts before failing. I think it is hitting a nil value that isn't quite nil for some of the contacts and then crashing.. I do have the following check for it though and it is passing through:
if ABRecordCopyValue(person, kABPersonFirstNameProperty).takeRetainedValue() as AnyObject? != nil{
&
if ABRecordCopyValue(person, kABPersonLastNameProperty).takeRetainedValue() as AnyObject? != nil{
respectively.
Update 3: Okay. So Now it seems whenever there is a blank field for first or last name it crashes (on the simulator now too). Which really sucks because I thought I put in a good check to make sure I am not accessing nil valued properties. Whats even more annoying is that I haven't changed this code and it was working fine until I removed some derived data and changed the test file to avoid a linker error. Anything that could happen in the build process that is mucking up my code?
Basically, you need to really check your type casts when accessing the addressbook, see:
tempPerson.lastname = ABRecordCopyValue(person, kABPersonLastNameProperty).takeRetainedValue() as NSObject as? String ?? ""
The problem is that some people have really dirty addressbooks for a variety of reasons and even have some mixed up properties like having a last name property that contains "LastName, FirstName SPACE Birthday" with no firstname property.
For whatever reason, typecasting first as an NSObject BEFORE as a String seems to work well.

Resources