What is this Objective C code in swift?

Viewed 742

I have found a solution to my problem, but the code is in Objective C. Please could someone tell me what this is in swift?

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

Thanks.

3 Answers

Try this :

do {
       try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
       try AVAudioSession.sharedInstance().setActive(true)
       UIApplication.shared.beginReceivingRemoteControlEvents()

   }catch{
        print("error")
   }

And further, if you need to convert any code from Objective C to Swift you can convert by using the following Link.

https://objectivec2swift.com

Try with this:

do{ 
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
    try AVAudioSession.sharedInstance().setActive(true)
    UIApplication.shared.beginReceivingRemoteControlEvents()
}catch {
   print("error")
}

Also, you can do it from XCode.

  1. Select the ObjC code that you want to convert.
  2. Go Editor > Swiftify > Convert Selection to Swift
  3. Done

Here is the full conversion of the code :

do {
  try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
  try AVAudioSession.sharedInstance().setActive(true)
  UIApplication.shared.beginReceivingRemoteControlEvents()
} catch {
  //handle error
  print(error)
}

The best way to convert the objective-c code would be to check out the latest documentation. Go to Xcode > Window > Developer Documentation, and then search for the class (e.g. AVAudioSession in this case)

Related