ios - nil while unwrapping an optinal value SWIFT -
this question has answer here:
i have downloaded project https://github.com/doberman/speaker-gender-detect--ios. followed instructions when run app, message says: fatal error: unexpectedly found nil while unwrapping optional value. how can fix crash app works.
the app crashes here:
let genderequalityratios = self.calcgenderequality (string (response.result.value!))
this code:
import avfoundation import alamofire import swiftyjson protocol audiorecorderdelegate { func audiorecorder(audiorecorder: audiorecorder?, updatedlevel: float) func audiorecorder(audiorecorder: audiorecorder?, updatedgenderequalityratio: (male: float, female: float)) } class audiorecorder: nsobject { static let sharedinstance: audiorecorder = audiorecorder() private let kremoteurl: nsurl = nsurl(string: "xxx.xxx.xxx.xxx")! // change api endpoint url private let kpostaudiointerval: nstimeinterval = 10.0 // change post api more/less var delegate: audiorecorderdelegate? private let recordersettings = [ avsampleratekey: nsnumber(float: float(16000.0)), avformatidkey: nsnumber(int: int32(kaudioformatmpeg4aac)), avnumberofchannelskey: nsnumber(int: 1), avencoderaudioqualitykey: nsnumber(int: int32(avaudioquality.high.rawvalue)) ] private var recorder: avaudiorecorder? private var checklevelstimer: nstimer? private var posttimer: nstimer? private var maleduration: float = 0.0 private var femaleduration: float = 0.0 override init() { super.init() { let audiosession: avaudiosession = avaudiosession.sharedinstance() try audiosession.setcategory(avaudiosessioncategoryrecord) } catch let err nserror { print("failed initialize audiorecorder: \(err)") } } func startrecording() { // print("startrecording") if self.recorder != nil && self.recorder!.recording { self.stoprecording() } let audiourl: nsurl = self.getaudiourl() // print("got audiourl: '\(audiourl)'") { self.recorder = try avaudiorecorder(url: audiourl, settings: self.recordersettings) self.recorder?.meteringenabled = true self.recorder?.preparetorecord() } catch let err nserror { print("failed set avaudiorecorder instance: \(err)") } guard self.recorder != nil else { return } self.recorder?.record() let audiosession = avaudiosession.sharedinstance() { try audiosession.setactive(true) self.checklevelstimer = nstimer.scheduledtimerwithtimeinterval(0.05, target: self, selector: "checklevels", userinfo: nil, repeats: true) self.posttimer = nstimer.scheduledtimerwithtimeinterval(kpostaudiointerval, target: self, selector: "onposttimertrigger", userinfo: nil, repeats: true) } catch let err nserror { print("failed activate audio session (or failed set checklevels timer): \(err)") } } func stoprecording(shouldsubmitaudioafterstop: bool = false) { // print("stoprecording") guard self.recorder != nil else { print("`self.recorder` `nil` - no recording stop") return } self.recorder?.stop() if let t = self.checklevelstimer { t.invalidate() self.checklevelstimer = nil } if let t = self.posttimer { t.invalidate() self.posttimer = nil } let audiourl: nsurl = self.recorder!.url self.recorder = nil let audiosession = avaudiosession.sharedinstance() { try audiosession.setactive(false) if shouldsubmitaudioafterstop { self.postaudio(audiourl) } else { // print("`shouldsubmitaudioafterstop` `false` - won't post audio") } } catch let err nserror { print("failed deactivate audio session (or failed post audio): \(err)") } } // mark: - func checklevels() { guard self.recorder != nil else { print("`self.recorder` `nil` - can't check levels") return } self.recorder?.updatemeters() let averagepower: float = self.recorder!.averagepowerforchannel(0) if let d = self.delegate { d.audiorecorder(self, updatedlevel: averagepower) } else { print("audiorecorder - averagepower: \(averagepower)") } } func onposttimertrigger() { // print("onposttimertrigger") guard let r = self.recorder else { print("`self.recorder` `nil` - no audio post") return } if !r.recording { print("not recording - no audio post") } self.stoprecording(true) self.startrecording() } // mark: - private func getaudiourl(filename: string = "recording") -> nsurl { let filemanager: nsfilemanager = nsfilemanager.defaultmanager() let urls: [nsurl] = filemanager.urlsfordirectory(.documentdirectory, indomains: .userdomainmask) let documentdirectory: nsurl = urls[0] nsurl let uniquefilename = "\(filename)_\(nsdate().timeintervalsince1970)" let audiourl: nsurl = documentdirectory.urlbyappendingpathcomponent("\(uniquefilename).m4a") return audiourl } private func postaudio(audiourl: nsurl) { // print("audiorecorder.postaudio - audiourl: \(audiourl.absolutestring)") alamofire.upload(method.post, kremoteurl, multipartformdata: { multipartformdata in multipartformdata.appendbodypart(fileurl: audiourl, name: "file") }, encodingcompletion: { encodingresult in switch encodingresult { case .success (let upload, _, _): upload.responsestring { response in //print("response: \(response)") let genderequalityratios = self.calcgenderequality(string(response.result.value!)) if let eq = genderequalityratios, let d = self.delegate { d.audiorecorder(self, updatedgenderequalityratio: eq) } } case .failure(let encodingerror): print("encodingerror: \(encodingerror)") } }) } private func calcgenderequality(response: string) -> (male: float, female: float)? { guard let datafromstring = response.datausingencoding(nsutf8stringencoding, allowlossyconversion: false) else { return nil } let json = json(data: datafromstring) selection in json["selections"].arrayvalue { if selection["gender"] == "m" { self.maleduration = self.maleduration + (selection["endtime"].floatvalue - selection["starttime"].floatvalue) } else if selection["gender"] == "f" { self.femaleduration = self.maleduration + (selection["endtime"].floatvalue - selection["starttime"].floatvalue) } } let spokenduration = self.maleduration + self.femaleduration let malefactor = self.maleduration / spokenduration let femalefactor = self.femaleduration / spokenduration guard !malefactor.isnan else { print("failed calculate gender equality (`malefactor` `nan`)") return nil } guard !femalefactor.isnan else { print("failed calculate gender equality (`femalefactor` `nan`)") return nil } return (male: malefactor, female: femalefactor) } }
try this:
if let genderequalityratios = response.result.value as? string { self.calcgenderequality(genderequalityratios) } else { print("a problem occurred , couldn't call calcgenderequality") }
Comments
Post a Comment