Мое приложение иногда дает сбой во время выполнения, когда я использую AVFoundation и связанный с ним код.IOS

Программируем под IOS
Ответить
Anonymous
 Мое приложение иногда дает сбой во время выполнения, когда я использую AVFoundation и связанный с ним код.

Сообщение Anonymous »

Я разрабатываю приложение для владельцев транспортных средств со встроенной функцией навигации по карте и поддержкой голосовой навигации. Приложение работает нормально без голосовой навигации, но когда я использую голосовую навигацию, оно иногда дает сбой, и оно вылетает, пока голосовая навигация не выполняется.
Что делает невозможным диагностику, так это то, что даже несмотря на сбой 10 раз на TestFlight я не вижу отчетов о сбоях в Apple Connect. Я попробовал запустить его в симуляторе, и там он не вылетел! но на реальном устройстве, когда я еду с приложением, осуществляющим навигацию, оно внезапно вылетает через несколько минут, и это происходит не тогда, когда говорит голосовая навигация! Я также запускал приложение без AVFoundation, и оно не вылетело. Так что я на 100% уверен, что это что-то с инфраструктурой AVFoundation.
Если кто-нибудь сможет помочь найти проблему в моем следующем коде, это будет очень полезно.
//
// DirectionsView.swift
// Map
//
// Created by saj panchal on 2023-12-10.
//

import SwiftUI
///framework to record, playback and stream parsing. Also provides interfaces to manage audio sessions
//import AudioToolbox
///framework that contains tasks to inspect, play, capture and process the audio video content.
import AVFoundation
///a view responsible to show the direction signs along with the instruction text on top of the screen while navigating.
struct DirectionHeaderView: View {
///environment variable to get the color mode of the phone
@Environment(\.colorScheme) var bgMode: ColorScheme
///variable that stores the image name for various direction signs.
var directionSign: String?
///stores distance from the next step in string format.
var nextStepDistance: String
///stores the instruction string.
var instruction: String
///flag that is bound to MapSwiftUI. it is set when user taps on this view to see the expanded directions list view.
@Binding var showDirectionsList: Bool
@Binding var height: CGFloat
///locationDataManager is an instance of a class that has a delegate of LocationManager and its methods.
@StateObject var locationDataManager: LocationDataManager
///AVSpeechSynthesizer class is responsible to create a synthesized speech from text utterances. it also play, pause or stop the speech based on the requirements.
@State private var synthesizer = AVSpeechSynthesizer()
///AVAudioSession is responsible to create an audio session sharedInstance that acts as a mediator between this app and the phone os. And, it creates an audio session based on the preferences.
@State private var audioSession = AVAudioSession.sharedInstance()
@State private var lastInstruction: String = ""
@State private var utteranceDistance: String = ""
@State private var isStepExited = false
@State private var range = 20.0
var body: some View {
VStack {
///enclosing the directions and instruction view in horizontal stack.
HStack {
///shows direction sign and next step distance below it.
VStack {
///if directionSign is not empty show the image.
if let directionSign = directionSign {
Image(systemName: directionSign)
.font(.title)
.fontWeight(.black)
.padding(.top, 5)
.foregroundStyle(.gray)

}
///show the distance from next step
if !instruction.contains("Re-calculating the route...") {
Text("\(nextStepDistance)")
.padding(.bottom, 5)
.font(.title2)
.fontWeight(.black)
.foregroundStyle(Color(AppColors.invertRed.rawValue))
.onChange(of: nextStepDistance) {
let distance = getDistanceInNumber(distance: nextStepDistance)

if distance Double {
var thisStepDistance = getDistanceInNumber(distance: distance)

if thisStepDistance != 0 {
switch thisStepDistance {
case 0...200:
if locationDataManager.speed >= 90 {
return thisStepDistance/1.5
}
else {
return thisStepDistance/2
}
case 201...300:
if locationDataManager.speed >= 90 {
return 120
}
else {
return 100
}
case 301...500:
if locationDataManager.speed >= 90 {
return 150
}
else {
return 125
}
case 501...1000:
if locationDataManager.speed >= 90 {
return 250
}
else {
return 200
}
case 1001...10000:
if locationDataManager.speed >= 90 {
return 250
}
else {
return 200
}

default:
if locationDataManager.speed >= 90 {
return 250
}
else {
return 200
}

}
}

return 200
}
func getDistanceInNumber(distance: String) -> Double {
var thisStepDistance = 0.0
if distance.contains("km") {
let stepDistanceSplits = distance.split(separator: " ")
let stepDistanceText = String(stepDistanceSplits[0])
if let dist = Double(stepDistanceText) {
thisStepDistance = dist * 1000
}

}
else {
var stepDistanceSplits = distance.split(separator: " ")
var stepDistanceText = String(stepDistanceSplits[0])
if let dist = Double(stepDistanceText) {
thisStepDistance = dist
}
}
print("Converted number: \(thisStepDistance)")
return thisStepDistance
}
}

#Preview {
DirectionHeaderView(directionSign: "", nextStepDistance: "", instruction: "", showDirectionsList: .constant(false), height: .constant(0), locationDataManager: LocationDataManager())
}


Подробнее здесь: https://stackoverflow.com/questions/791 ... lated-code
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «IOS»