Learn Courses My Dashboard

Errors sending me in circles - Please help - Thread 1: Fatal error: init(coder:) has not been implemented - then

HI - so I am creating an app that includes an audio player that is accessed through a button called from the main page once the user has logged into their account. All of the pages of the app have been created using Storyboards but the audio player is done programmatically with SwiftUI. The app runs fine until you press the button to access the audio player. Then I get “Thread 1: Fatal error: init(coder:) has not been implemented” on the AudioPlayerViewController. So I searched for a solution online and as per the suggestions, removed this:

required init?(coder: NSCoder) {
fatalError(“init(coder:) has not been implemented”)
}

And put this instead as suggested on StackOverflow:

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}

But then I get this error:

“Property ‘self.album’ not initialized at super.init call”

so I add: " self.album = album" - as you see below:

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.album = album

}

But then I get the error: “Assigning a property to itself”

And now I’m tired. Send help.

Welcome to the community!

Don’t remove this.

But it seems like you have an issue for how your UIKit is talking to SwiftUI

Can you attach your full file of code that you’re talking about?

Paste your code in as text, rather than providing a screenshot.

To format the code nicely, place 3 back-ticks ``` on the line above your code and 3 back-ticks ``` on the line below your code. The 3 back-ticks must be the ONLY characters on the line. The back-tick character is located on the same keyboard key as the tilde character ~ (which is located below the Esc key). You can also highlight an entire code block and click the </> button on the toolbar to wrap the block for you.

This also makes it easier for anyone assisting as they can copy the code and carry out some testing.

Hi! Thank you! ok, i put it back and below is the whole code for that file:

// AudioPlayerViewController.swift - just the design elements

import UIKit

final class AudioPlayerViewController: UIViewController {
    var album: Album
    
    private lazy var mediaPlayer: MediaPlayer = {
        let v = MediaPlayer(album: album)
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()
    
    init(album: Album) {
        self.album = album
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//    required init?(coder aDecoder: NSCoder) {
//       super.init(coder: aDecoder)
//        self.album = album
//
//    }
//    override func awakeFromNib() {
//       super.awakeFromNib()
//       //custom logic goes here
//    }
//
    override func viewDidLoad() {
        super.viewDidLoad()
        setupView()
    }
    
    private func setupView() {
        addBlurredView()
        view.addSubview(mediaPlayer)
        
        setupConstraints()
    }
    
    private func addBlurredView() {
        if !UIAccessibility.isReduceTransparencyEnabled {
            self.view.backgroundColor = UIColor.clear
            
            let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.dark)
            let blueEffectView = UIVisualEffectView(effect: blurEffect)
            blueEffectView.frame = self.view.bounds
            blueEffectView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
            
            view.addSubview(blueEffectView)
        } else {
            view.backgroundColor = UIColor.black
        }
    }
    
    private func setupConstraints() {
        NSLayoutConstraint.activate([
            mediaPlayer.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            mediaPlayer.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            mediaPlayer.topAnchor.constraint(equalTo: view.topAnchor),
            mediaPlayer.bottomAnchor.constraint(equalTo: view.bottomAnchor),
        ])
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        mediaPlayer.play()
        UIApplication.shared.isIdleTimerDisabled = true
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        mediaPlayer.stop()
        UIApplication.shared.isIdleTimerDisabled = false
    }
}

What’s the code for this button press? That triggers the error

here is the code for the “SearchFormViewController” file with the button press :

//
//  SearchFormViewController.swift
//  mmm
//
//  Created by AM Devito on 2022-02-03.
//

import UIKit
import MapKit
import CoreLocation

class SearchFormViewController: UIViewController {
    
    
    @IBOutlet weak var listenNowButton: UIButton!
    
    @IBAction func didTapListenNowButton(){
        
        guard let vc = self.storyboard?.instantiateViewController(identifier: "audioPlayer") as? AudioPlayerViewController else {  print("Failed to get vc from storyboard")
        return

            }
        present(vc, animated: true)
    }
    

    @IBOutlet weak var mapView: MKMapView!
    
    private var audioGems: [AudioGems] = []
    
  
    
    var locationManager: CLLocationManager!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Set initial location in Montreal
        let initialLocation = CLLocation(latitude: 45.54324, longitude: -73.58715)

        mapView.centerToLocation(initialLocation)


        // Do any additional setup after loading the view.
        locationManager = CLLocationManager()
        locationManager.requestWhenInUseAuthorization()
        locationManager.requestAlwaysAuthorization()
 
        let cityCentre = CLLocation(latitude: 45.5432, longitude: -73.5871)
        let region = MKCoordinateRegion(
          center: cityCentre.coordinate,
          latitudinalMeters: 50000,
          longitudinalMeters: 60000)
        mapView.setCameraBoundary(
          MKMapView.CameraBoundary(coordinateRegion: region),
          animated: true)
        
        let zoomRange = MKMapView.CameraZoomRange(maxCenterCoordinateDistance: 200000)
        mapView.setCameraZoomRange(zoomRange, animated: true)
        
        mapView.delegate = self
        
        mapView.register(
          AudioGemsView.self,
          forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)
        
        loadInitialData()
        mapView.addAnnotations(audioGems)
      }
      
    private func loadInitialData() {
      // 1
      guard
        let fileName = Bundle.main.url(forResource: "MMMContent", withExtension: "geojson"),
        let audioGemsData = try? Data(contentsOf: fileName)
        else {
          return
      }
      
      do {
        // 2
        let content = try MKGeoJSONDecoder()
          .decode(audioGemsData)
          .compactMap { $0 as? MKGeoJSONFeature }
        // 3
        let validGems = content.compactMap(AudioGems.init)
        // 4
        audioGems.append(contentsOf: validGems)
      } catch {
        // 5
        print("Unexpected error: \(error).")
      }
    }
  }



extension ViewController: CLLocationManagerDelegate {
    
    // iOS 14
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        if #available(iOS 14.0, *) {
            switch manager.authorizationStatus {
            case .notDetermined:
                print("Not determined")
            case .restricted:
                print("Restricted")
            case .denied:
                print("Denied")
            case .authorizedAlways:
                print("Authorized Always")
            case .authorizedWhenInUse:
                print("Authorized When in Use")
            @unknown default:
                print("Unknown status")
            }
        }
    }
}
private extension MKMapView {
  func centerToLocation(
    _ location: CLLocation,
    regionRadius: CLLocationDistance = 30000
  ) {
    let coordinateRegion = MKCoordinateRegion(
      center: location.coordinate,
      latitudinalMeters: regionRadius,
      longitudinalMeters: regionRadius)
    setRegion(coordinateRegion, animated: true)
  }
}

extension SearchFormViewController: MKMapViewDelegate {
  func mapView(
    _ mapView: MKMapView,
    annotationView view: MKAnnotationView,
    calloutAccessoryControlTapped control: UIControl
  ) {
    guard let audioGems = view.annotation as? AudioGems else {
      return
    }
    
    let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]
    audioGems.mapItem?.openInMaps(launchOptions: launchOptions)///
  }
}

Anyone else help?

Is your button connected to the IBAction correctly?

And in your storyboard your view controller class is set properly?

I think so? Before I created the musicPlayerViewController programmatically, I created a placeholder page with just the text “audio player” and when I pressed the Listen now button it successfully took me to that page.