How can I replace deprecated method dispatch_get_current_queue()? [duplicate] - iphone

This question already has answers here:
Alternatives to dispatch_get_current_queue() for completion blocks in iOS 6?
(7 answers)
Closed 9 years ago.
I am developing a chat application using xmppframework in iOS 5; it works perfectly.
But I updated my Xcode to 4.5.1, iOS 5 to iOS 6 and my Mac OS to 10.7.5, and the project did not work due to deprecation issues. I replaced all methods with new methods in iOS 6 except this one:
dispatch_get_current_queue()
How can I replace this method in iOS 6?

It depends what you need to achieve with this call.
Apple states that it should be used for debugging anyway.
Perhaps the queue does not matter (as you just need a background queue) so get a global queue with specific priority (dispatch_get_global_queue(dispatch_queue_priority_t priority,
unsigned long flags);)
OR,
If you do need to execute some pieces of code in the same queue , create a queue, retain it and dispatch all your tasks there.

How about using NSOperationQueue?
-(void) doSomeThing:(void (^)(BOOL success)) completionHandler
{
NSOperationQueue* callbackQueue = [NSOperationQueue currentQueue];
if(!callbackQueue) {
callbackQueue = [NSOperationQueue mainQueue];
}
dispatch_async(...,^{
// do heavyweight stuff here
// then call completionHandler
if(completionHandler) {
[callbackQueue addOperationWithBlock:^{
completionHandler(...);
}];
}
});

Related

Background tasks in swift 3

What is equivalent of respond to selector for background tasks? I found the code in Objective-C. I'm trying to get the same in Swift.
Here is the Objective-C code:
if ([application respondsToSelector:#selector(beginBackgroundTaskWithExpirationHandler:)]){
bgTaskId = [application beginBackgroundTaskWithExpirationHandler:^{
})
Swift code:
if application.responds(to: #selector(self.beginBackgroundTaskWithExpirationHandler)) {
bgTaskId = application.beginBackgroundTask(expirationHandler: {() -> Void in
print("background task \(UInt(bgTaskId!)) expired")
})
It's saying BackgroundTaskManager has no member 'beginBackgroundTaskWithExpirationHandler'.
What is the exact thing we can replicate in Swift 3?
Unless you are attempting to support iOS 3 or earlier, there is no need to check for the existence of the selector since it was added in iOS 4.0.
But the Swift selector would be: beginBackgroundTask(expirationHandler:).
Here's a simple trick when trying to convert an Objective-C API into Swift. Pull up the API documentation in Xcode or online. Choose the Objective-C APIs. Find the method you wish to convert. Then switch the documentation to the Swift APIs. In a case like this you will now see the same method but in Swift.

'NSInvocationOperation' is unavailable in Xcode 6.1

My code suddenly can't be compiled in Xcode 6.1 (I'm sure it's working in Xcode 6 GM and beta version). It shows the error message:
'NSInvocationOperation' is unavailable
My code is:
let operation = NSInvocationOperation(target:self, selector:"backgroundRun:", object:self)
Can anybody help? Thanks.
As of Xcode 6.1, NSInvocation is disabled in Swift, therefore, NSInvocationOperation is disabled too. See this thread in Developer Forum
Because it's not type-safe or ARC-safe. Even in Objective-C it's very very easy to shoot yourself in the foot trying to use it, especially under ARC. Use closures/blocks instead.
You have to use NSBlockOperation in Swift.
or addOperationWithBlock to NSOperationQueue
queue.addOperationWithBlock { [weak self] in
self?.backgroundRun(self)
return
}

CBCentralManager changes for iOS 7

I am trying to use Apple's 'BTLE Transfer' sample project to understand CoreBluetooth programming. The app runs fine if I use an iOS 6 device as the Central, but if I run the same app with the iOS 7 device as the Central it doesn't work. The peripheral stops sending after two packets, and the central doesn't receive either one of them.
The only clue is this warning that I get only when running on iOS 7:
CoreBluetooth[WARNING] <CBCentralManager: 0x15654540> is disabling duplicate filtering, but is using the default queue (main thread) for delegate events
Can anyone tell me what needs to change to make this app compatible with iOS 7?
EDIT: When both devices are iOS7 there are no issues. This only breaks when an iOS7 central is talking to a iOS6 peripheral.
Okay I just ran it on an iOS 7 central to iOS 6 peripheral. If you want to make that warning about disabling duplicate filtering go away, just run it on a different thread. Do something like this:
dispatch_queue_t centralQueue = dispatch_queue_create("com.yo.mycentral", DISPATCH_QUEUE_SERIAL);// or however you want to create your dispatch_queue_t
_centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:centralQueue];
Now it will allow you to scan with duplicates enabled. However, you must call the textView setter on the main thread to be able to set the text without crashing:
dispatch_async(dispatch_get_main_queue(), ^{
[self.textview setText:[[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding]];
});
Btw you probably also want to adopt the new iOS 7 delegate initialization:
_centralManager = [[CBCentralManager alloc]initWithDelegate:self queue:centralQueue options:nil];//set the restoration options if you want
(Just check the iOS version and call the appropriate initialization method)
InscanForPeripheralsWithServices:options:,if you set CBCentralManagerScanOptionAllowDuplicatesKey:#YES then change it to
CBCentralManagerScanOptionAllowDuplicatesKey:#NOthat means scan should run without duplicate filtering.
For me,it works on iOS7 also.

iOS 4 and iOS 5 backward compatibility

I have a question regarding iOS 4 and 5. I am really confused and hope someone will clear it out for me.
I am using iOS 5 SDK in my application. If i use the iOS 5 Twitter integration which is provided by apple, will it run on an iPhone that has iOS 4 installed ?
Does backward compatibility work ?
I have used Twitter as an example, but does backward compatibility really work with iOS 5 ?
If you set up your app properly, so that it can be run on devices running iOS 4 without crashing, then: yes, it will run on an iPhone that has iOS 4 installed.
Your app should implement logic such that the Twitter API is used when the app is being run on an iOS 5 device. When the app is running on an iOS 4 device, you can conditionally choose not to use the Twitter API.
Instead, you can use a different Twitter library (like MGTwitterEngine, or your own) - or just exclude Twitter functionality for those users.
To check whether the TWRequest Class exists, use NSClassFromString.
Class twRequestClass = NSClassFromString(#"TWRequest");
if (twRequestClass == nil) {
// TWRequest does not exist on this device (running iOS version < 5.0)
// ... do something appropriate ...
} else {
TWRequest *twRequest = [[twRequestClass alloc] init];
// ^ I didn't look up the proper initializer, so you should change that line if necessary
// ...
}
You would have to create ifs dependently of the iOS version the user is using. Exemple, in iOS 5 there is an Appearance API to modify most of the UI, but not in iOS 4, so you have to create a little if like that:
// not supported on iOS4
UINavigationBar *navBar = [myNavController navigationBar];
if ([navBar respondsToSelector:#selector(setBackgroundImage:forBarMetrics:)])
{
[navBar setBackgroundImage:[UIImage imageNamed:#"bg.jpg"] forBarMetrics:UIBarMetricsDefault];
}
If you set up your app properly, so that it can be run on devices running iOS 4, it will crash. This is because you're trying to access methods/features that arn't available.
The way to get around this is to check if a feature is available using
if(NSClassFromString(#"UIPopoverController")) {
// Do something
}
(Popover controller is just an example)
You could also check the version using
float version = [[[UIDevice currentDevice] systemVersion] floatValue];
And then depending on the version run a specific piece of code (i.e. if iOS 5, preform twitter stuff,else do something different)
No, if you use the Twitter APIs available in iOS5, they will not be able to run on iOS4.
The reason being that when app will run on iOS4, the system will not be having the APIs availability.
if you check the documentation, you can see the iOS version from where this Class/API is available.
I hope this helps..

ios: add printing, but keep compatibility with ios 3

i'm trying to add printing features to an ios app.
while printing itself works fine, and the app works on ios > 4, i haven't figured out yet how to keep the ios 3.1 compatibility...
i guess the issue is this: completionHandler:(UIPrintInteractionCompletionHandler)
A block of type UIPrintInteractionCompletionHandler that you implement to handle the
conclusion of the print job (for instance, to reset state) and to
handle any errors encountered in printing.
once i add the block:
void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) =
^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
};
the app won't even launch on iOS 3.1
probably because blocks aren't available there.
yes, i made sure that this code won't be run when launched on iOS 3.1...
if (([[[UIDevice currentDevice] systemVersion] floatValue] >= 4.2) && ([UIPrintInteractionController isPrintingAvailable]))
so i wonder if there's a way to have printing support for iOS >4.2, but keeping it to run on iOS 3.1?
maybe there's a way to use a method instead of the "block"?
or how would be the correct way to have printing available on supported iOS devices, and remain backwards compatible to iOS 3.1?
just add -weak_framework UIKit to the project settings under "Other Linker Flags" and make sure you use conditional code for printing API.
Conditional code should check feature availability, not OS version:
if (NSClassFromString(#"UIPrintInteractionController")){
void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) =
^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
};
}
Set your project target to iOS 3, and you're good to go.
The best practice for detecting if AirPrint is available is to use NSClassFromString. If you use this method in general, then you always know if exactly the class you want is available, without having to hard-code which features correspond with which version. Example code:
Class printControllerClass = NSClassFromString(#"UIPrintInteractionController");
if (printControllerClass) {
[self setupCanPrintUI];
} else {
[self setupCannotPrintUI];
}
That way your app can still work on previous iOS versions, although it won't be able to print from them.
I've been able to use this technique and run it on an iOS 3.0 device without any problems with the block code (the ^-based stuff). In my build settings, I have the Base SDK set to iOS 4.2, and the Deployment Target set to iOS 3.0.
I posted a sample Xcode project at the end of this blog post on printing in iOS. This is the project that successfully runs for me on a device with iOS 3.0 and another device with iOS 4.2. You may have to change the bundle identifier in the info.plist to get the code-signing to work for you, but that's independent of the printing stuff.
Set Deployment Target in your Project Settings to iOS 3.x. However, set the Base SDK to 4.2. Now you can use the 4.2 classes and iPhones running 3.x can install your app too.
Keep in mind that when you use a 4.2 class on an iPhone 3.x, the application will crash (so keep checking the system version on-the-go).
NSComparisonResult order = [[UIDevice currentDevice].systemVersion compare:#"3.2" options: NSNumericSearch];
if (order == NSOrderedSame || order == NSOrderedDescending && [[UIDevice currentDevice]isMultitaskingSupported]) {
// >4.2
}
else {
//< 4.2
}
Note:
also change UIKit framework setting from "required" to "weak" this will help you to run application on iOs < 4.2 as well as iOs >= 4.2