SwiftUI | How to display video title in control center of iPhone - swiftui

I want to display video title in control center of iPhone. But, the title does not appear. What should I do?
Xcode 14.0, Swift 5.7, iPhone8 iOS 16.0
import SwiftUI
import AVKit
import MediaPlayer
struct ContentView: View {
var body: some View {
let playerClass = PlayerClass()
VideoPlayer(player: playerClass.aVPlayer)
.onAppear {
playerClass.aVPlayer.play()
}
}
}
class PlayerClass {
var aVPlayer: AVPlayer
init() {
let fileUrl = Bundle.main.url(forResource: "sample",
withExtension: "mp4")!
aVPlayer = AVPlayer(url: fileUrl)
setNowPlayingInfo()
setMPRemoteCommandCenter()
}
func setNowPlayingInfo() {
var nowPlayingInfo = [String : Any]()
nowPlayingInfo[MPMediaItemPropertyTitle] = "my title"
nowPlayingInfo[MPMediaItemPropertyAlbumTitle] = "my album"
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
}
func setMPRemoteCommandCenter() {
let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.playCommand.addTarget { [unowned self] event in
print("play")
return .success
}
commandCenter.pauseCommand.addTarget { [unowned self] event in
print("pause")
return .success
}
}
}
I expect the video title appears in control center.

Related

SwiftUI Search Bar in line with navigation bar

Does anyone have working Swiftui code that will produce a search bar in the navigation bar that is inline with the back button? As if it is a toolbar item.
Currently I have code that will produce a search bar below the navigation back button but would like it in line like the picture attached shows (where the "hi" is):
I am using code that I found in an example:
var body: some View {
let shopList = genShopList(receiptList: allReceipts)
VStack{
}
.navigationBarSearch(self.$searchInput)
}
public extension View {
public func navigationBarSearch(_ searchText: Binding<String>) -> some View {
return overlay(SearchBar(text: searchText)
.frame(width: 0, height: 0))
}
}
fileprivate struct SearchBar: UIViewControllerRepresentable {
#Binding
var text: String
init(text: Binding<String>) {
self._text = text
}
func makeUIViewController(context: Context) -> SearchBarWrapperController {
return SearchBarWrapperController()
}
func updateUIViewController(_ controller: SearchBarWrapperController, context: Context) {
controller.searchController = context.coordinator.searchController
}
func makeCoordinator() -> Coordinator {
return Coordinator(text: $text)
}
class Coordinator: NSObject, UISearchResultsUpdating {
#Binding
var text: String
let searchController: UISearchController
private var subscription: AnyCancellable?
init(text: Binding<String>) {
self._text = text
self.searchController = UISearchController(searchResultsController: nil)
super.init()
searchController.searchResultsUpdater = self
searchController.hidesNavigationBarDuringPresentation = true
searchController.obscuresBackgroundDuringPresentation = false
self.searchController.searchBar.text = self.text
self.subscription = self.text.publisher.sink { _ in
self.searchController.searchBar.text = self.text
}
}
deinit {
self.subscription?.cancel()
}
func updateSearchResults(for searchController: UISearchController) {
guard let text = searchController.searchBar.text else { return }
self.text = text
}
}
class SearchBarWrapperController: UIViewController {
var searchController: UISearchController? {
didSet {
self.parent?.navigationItem.searchController = searchController
}
}
override func viewWillAppear(_ animated: Bool) {
self.parent?.navigationItem.searchController = searchController
}
override func viewDidAppear(_ animated: Bool) {
self.parent?.navigationItem.searchController = searchController
}
}
}
If anyone has a solution to this problem that would be greatly appreciated! I know that in IoS 15 they are bringing out .searchable but looking for something that will work for earlier versions too.
You can put any control in the position you want by using the .toolbar modifier (iOS 14+) and an item with .principal placement, e.g.:
var body: some View {
VStack {
// rest of view
}
.toolbar {
ToolbarItem(placement: .principal) {
MySearchField(text: $searchText)
}
}
}
A couple of things to note:
The principal position overrides an inline navigation title, either when it's set with .navigationBarTitleDisplayMode(.inline) or when you have a large title and scroll up the page.
It's possible that your custom view expands horizontally so much that the back button loses any text component. Here, I used a TextField to illustrate the point:
You might be able to mitigate for that by assigning a maximum width with .frame(maxWidth:), but at the very least it's something to be aware of.

Why AVAudioPlayer has no sound?

I got one button which can play and pause the audio, but I found the following code has no sound. Do you know why? If I put the AVAudioPlayer create code snippet in a dependent function playAudio(), it can play the sound but I cannot pause and continue playing.
Reproducible code
import SwiftUI
import AVFoundation
struct ContentView: View {
var shortname: String
var id: Int
#State var audioPlayer: AVAudioPlayer?
init(shortname: String="rs", id: Int=1) {
self.shortname = shortname
self.id = id
let fileName = self.shortname.lowercased() + "-" + String(id)
guard let path = Bundle.main.path(forResource: fileName, ofType: "mp3") else {
print("[shark]", fileName + "is not found")
return
}
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
audioPlayer?.play()
} catch {
print("[shark], audioPlayer cannot load", path, error)
}
}
var body: some View {
Text("good")
.onAppear {
audioPlayer?.play()
}
}
}
SwiftUI is picky about what you can do in an initializer for a View struct like this. A more reliable option is to move the loading into an ObservableObject:
class AudioManager : ObservableObject {
var audioPlayer : AVAudioPlayer?
func loadAudio(filename: String) {
guard let path = Bundle.main.path(forResource: filename, ofType: "mp3") else {
print("[shark]", filename + "is not found")
return
}
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
} catch {
print("[shark], audioPlayer cannot load", path, error)
}
}
func playAudio() {
audioPlayer?.play()
}
}
struct ContentView: View {
var shortname: String = ""
var id: Int = 0
#ObservedObject var audioManager = AudioManager()
var body: some View {
Text("good")
.onAppear {
let fileName = self.shortname.lowercased() + "-" + String(id)
audioManager.loadAudio(filename: fileName)
audioManager.playAudio()
}
}
}
This plays for me on Xcode 12.3 and iOS 14

SwiftUI How to toggle a Bool in a Struct from an ObservableObject class and show alert to notify user

I have a method in my class that opens a map when given an address string. Trying to show an alert in a view by toggling a boolean in a method in the class. I can't figure out how to toggle the boolean in the class method. This is what I tried. The Published bool in class method updates but does not update in the View. I did put up a repo of just this feature if anybody wants to play around with it.
https://github.com/Ongomobile/LocationTest/tree/main/LocationTest
import SwiftUI
#main
struct LocationTestApp: App {
var body: some Scene {
WindowGroup {
ContentView(location: LocationManager())
}
}
}
Here is my Class:
import UIKit
import MapKit
import CoreLocation
import Combine
class LocationManager: NSObject, ObservableObject {
var locationManager = CLLocationManager()
lazy var geocoder = CLGeocoder()
#Published var locationString = "1140"
// #Published var locationString = "1 apple park way cupertino"
#Published var currentAddress = ""
#Published var isValid: Bool = true
func openMapWithAddress () {
geocoder.geocodeAddressString(locationString) { placemarks, error in
if let error = error {
self.isValid = false
// prints false but does not update
print("isValid")
print(error.localizedDescription)
}
guard let placemark = placemarks?.first else {
return
}
guard let lat = placemark.location?.coordinate.latitude else{return}
guard let lon = placemark.location?.coordinate.longitude else{return}
let coords = CLLocationCoordinate2DMake(lat, lon)
let place = MKPlacemark(coordinate: coords)
let mapItem = MKMapItem(placemark: place)
mapItem.name = self.locationString
mapItem.openInMaps(launchOptions: nil)
}
}
}
Here is the view:
import SwiftUI
struct ContentView: View {
#ObservedObject var locationManager = LocationManager()
#State private var showingAlert = false
var body: some View {
Button {
locationManager.openMapWithAddress()
} label: {
Text("Get Map")
}
.alert(isPresented: $showingAlert) {
Alert(title: Text("Important message"), message:
Text("Enter a valid address"), dismissButton:
.default(Text("OK")))
}
}
}
I updated this answer to reflect some refactor help that I got from #rlong405 I put up a repository with this solution maybe it could help others.
OpenMapsInSwiftUI
import SwiftUI
struct ContentView: View {
#ObservedObject var locationManager = LocationManager()
var body: some View {
VStack{
Form{
Section {
Text("Enter Address")
TextField("", text: $locationManager.locationString)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding(.horizontal)
}
Button {
locationManager.openMapWithAddress()
} label: {
Text("Get Map")
}
.alert(isPresented: $locationManager.invalid) {
Alert(title: Text("Important message"), message:
Text("Enter a valid address"), dismissButton:
.default(Text("OK"), action:{
locationManager.invalid = false
locationManager.locationString = ""
}))
}
}
}
}
}
import UIKit
import MapKit
import CoreLocation
import Combine
class LocationManager: NSObject, ObservableObject {
lazy var geocoder = CLGeocoder()
#Published var locationString = ""
#Published var invalid: Bool = false
func openMapWithAddress () {
geocoder.geocodeAddressString(locationString) { placemarks, error in
if let error = error {
DispatchQueue.main.async {
self.invalid = true
}
print(error.localizedDescription)
}
guard let placemark = placemarks?.first else {
return
}
guard let lat = placemark.location?.coordinate.latitude else{return}
guard let lon = placemark.location?.coordinate.longitude else{return}
let coords = CLLocationCoordinate2DMake(lat, lon)
let place = MKPlacemark(coordinate: coords)
let mapItem = MKMapItem(placemark: place)
mapItem.name = self.locationString
mapItem.openInMaps(launchOptions: nil)
}
}
}

SwiftUI - Location in API call with CLLocationManager and CLGeocoder

I'm struggling with this for a long time without finding where I'm wrong (I know I'm wrong).
I have one API call with the location of the phone (this one is working), but I want the same API call with a manual location entered by a textfield (using Geocoding for retrieving Lat/Long). The geocoding part is ok and updated but not passed in the API call.
I also want this API call to be triggered when the TextField is cleared by the dedicated button back with the phone location.
Please, what am I missing? Thanks for your help.
UPDATE: This works on Xcode 12.2 beta 2 and should work on Xcode 12.0.1
This is the code:
My Model
import Foundation
struct MyModel: Codable {
let value: Double
}
My ViewModel
import Foundation
import SwiftUI
import Combine
final class MyViewModel: ObservableObject {
#Published var state = State.ready
#Published var value: MyModel = MyModel(value: 0.0)
#Published var manualLocation: String {
didSet {
UserDefaults.standard.set(manualLocation, forKey: "manualLocation")
}
}
#EnvironmentObject var coordinates: Coordinates
init() {
manualLocation = UserDefaults.standard.string(forKey: "manualLocation") ?? ""
}
enum State {
case ready
case loading(Cancellable)
case loaded
case error(Error)
}
private var url: URL {
get {
return URL(string: "https://myapi.com&lat=\(coordinates.latitude)&lon=\(coordinates.longitude)")!
}
}
let urlSession = URLSession.shared
var dataTask: AnyPublisher<MyModel, Error> {
self.urlSession
.dataTaskPublisher(for: self.url)
.map { $0.data }
.decode(type: MyModel.self, decoder: JSONDecoder())
.receive(on: RunLoop.main)
.eraseToAnyPublisher()
}
func load(){
assert(Thread.isMainThread)
self.state = .loading(self.dataTask.sink(
receiveCompletion: { completion in
switch completion {
case .finished:
print("⚠️ API Call finished")
break
case let .failure(error):
print("❌ API Call failure")
self.state = .error(error)
}
},
receiveValue: { value in
self.state = .loaded
self.value = value
print("👍 API Call loaded")
}
))
}
}
The Location Manager
import Foundation
import SwiftUI
import Combine
import CoreLocation
import MapKit
final class Coordinates: NSObject, ObservableObject {
#EnvironmentObject var myViewModel: MyViewModel
#Published var latitude: Double = 0.0
#Published var longitude: Double = 0.0
#Published var placemark: CLPlacemark? {
willSet { objectWillChange.send() }
}
private let locationManager = CLLocationManager()
private let geocoder = CLGeocoder()
override init() {
super.init()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
}
deinit {
locationManager.stopUpdatingLocation()
}
}
extension Coordinates: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else { return }
latitude = location.coordinate.latitude
longitude = location.coordinate.longitude
geocoder.reverseGeocodeLocation(location, completionHandler: { (places, error) in
self.placemark = places?[0]
})
self.locationManager.stopUpdatingLocation()
}
}
extension Coordinates {
func getLocation(from address: String, completion: #escaping (_ location: CLLocationCoordinate2D?)-> Void) {
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address) { (placemarks, error) in
guard let placemarks = placemarks,
let location = placemarks.first?.location?.coordinate else {
completion(nil)
return
}
completion(location)
}
}
}
The View
import Foundation
import SwiftUI
struct MyView: View {
#EnvironmentObject var myViewModel: MyViewModel
#EnvironmentObject var coordinates: Coordinates
private var icon: Image { return Image(systemName: "location.fill") }
var body: some View {
VStack{
VStack{
Text("\(icon) \(coordinates.placemark?.locality ?? "Unknown location")")
Text("Latitude: \(coordinates.latitude)")
Text("Longitude: \(coordinates.longitude)")
}
VStack{
Text("UV Index: \(myViewModel.value.value)")
.disableAutocorrection(true)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
}
HStack{
TextField("Manual location", text: $myViewModel.manualLocation)
if !myViewModel.manualLocation.isEmpty{
Button(action: { clear() }) { Image(systemName: "xmark.circle.fill").foregroundColor(.gray) }
}
}
}.padding()
}
func commit() {
coordinates.getLocation(from: self.myViewModel.manualLocation) { places in
coordinates.latitude = places?.latitude ?? 0.0
coordinates.longitude = places?.longitude ?? 0.0
}
myViewModel.load()
}
func clear() {
myViewModel.manualLocation = ""
myViewModel.load()
}
}

How to make a SwiftUI DocumentGroup app without starting on the file picker?

If a user uses the Document App template in Xcode to create a SwiftUI app, macOS starts them off with a new document. This is good. I can work with that to present onboarding UI within a new document.
However, with that same app running on iOS, the user is instead greeted by the stock document view controller to create or pick a document.
This is not helpful in that I don't have a way to present onboarding or any other custom information.
I did notice that if you add a WindowGroup to the Scene, the app will display that window group. But then I don't know how to get the user to the picker UI.
Has anyone figured out how to do things like present onboarding on top of this DocumentGroup-based app?
Here is a full document app
import SwiftUI
import UniformTypeIdentifiers
#main
struct DocumentTestApp: App {
var body: some Scene {
DocumentGroup(newDocument: DocumentTestDocument()) { file in
ContentView(document: file.$document)
}
}
}
struct ContentView: View {
#Binding var document: DocumentTestDocument
var body: some View {
TextEditor(text: $document.text)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(document: .constant(DocumentTestDocument()))
}
}
extension UTType {
static var exampleText: UTType {
UTType(importedAs: "com.example.plain-text")
}
}
struct DocumentTestDocument: FileDocument {
var text: String
init(text: String = "Hello, world!") {
self.text = text
}
static var readableContentTypes: [UTType] { [.exampleText] }
init(configuration: ReadConfiguration) throws {
guard let data = configuration.file.regularFileContents,
let string = String(data: data, encoding: .utf8)
else {
throw CocoaError(.fileReadCorruptFile)
}
text = string
}
func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
let data = text.data(using: .utf8)!
return .init(regularFileWithContents: data)
}
}
App shows first window scene by default, so place first on-boarding window scene and afterwards a DocumentGroup. Somewhere at the end of on boarding process (success path) call document controller to create new document (DocumentGroup is based on same NSDocumentController engine inside).
Update: below is for macOS
*just recognised that original question is for iOS
So a possible approach is
#main
struct DocumentTestApp: App {
var body: some Scene {
WindowGroup("On-Boarding") {
// ContentView()
// In some action at the end of this scene flow
// just close current window and open new document
Button("Demo") {
NSApp.sendAction(#selector(NSWindow.performClose(_:)), to: nil, from: nil)
NSDocumentController.shared.newDocument(nil)
}
}
DocumentGroup(newDocument: DocumentTestDocument()) { file in
ContentView(document: file.$document)
}
}
}
Alright friends, here is a nice and hacky way to get things going, reaching into the key windows, and setting up onboarding/paywall/whatever you want!
import SwiftUI
#main
struct ExampleApp: App {
#StateObject var captain = Captain()
var body: some Scene {
DocumentGroup(newDocument: ExampleOfDocumentGroupAndOnboardingPaywallDocument()) { file in
ContentView(document: file.$document)
}
}
}
class Captain: ObservableObject {
var onboardingSheet: UIViewController?
#objc func loadData() {
onboardingSheet = try? OnboardingOrPaywall(dismissHandler: dismissSheet).presentFromDocumentGroup()
}
func dismissSheet() {
onboardingSheet?.dismiss(animated: true)
}
init() {
NotificationCenter.default.addObserver(self,
selector: #selector(loadData),
name: UIApplication.didBecomeActiveNotification,
object: nil)
}
}
public protocol DocumentGroupSheet: View {}
struct OnboardingOrPaywall: DocumentGroupSheet {
var dismissHandler: () -> Void
var body: some View {
Button("Done") {
dismissHandler()
}
Text("Let me introduce you to this delicious app!")
}
}
public enum DocumentGroupSheetError: Error {
case noParentWindow
}
public extension DocumentGroupSheet {
func presentFromDocumentGroup() throws -> UIViewController {
let window = UIApplication.shared.activeKeyWindows.first
let parent = window?.rootViewController
guard let parent = parent else { throw DocumentGroupSheetError.noParentWindow }
let sheet = UIHostingController(rootView: body)
sheet.modalPresentationStyle = .fullScreen
parent.present(sheet, animated: false, completion: nil)
return sheet
}
}
public extension UIApplication {
var activeWindowScenes: [UIWindowScene] {
connectedScenes
.filter { $0.activationState == .foregroundActive }
.compactMap { $0 as? UIWindowScene }
}
var activeWindows: [UIWindow] {
activeWindowScenes
.flatMap { $0.windows }
}
var activeKeyWindows: [UIWindow] {
activeWindows
.filter { $0.isKeyWindow }
}
}