我从XML解析中收到了一个base64字符串(字符串太长),我想将其转换为音频文件,然后将那个base64字符串转换为NSData并成功写入文档目录中,但是当我返回时该音频文件没有播放。有人面对吗?
func getPackages() {
let semaphore = DispatchSemaphore (value: 0)
let parameters = "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">\n <soap12:Body>\n <GetPackage xmlns=\"http://tempuri.org/\">\n <data>\n <UID>123</UID>\n <Platform>iOS</Platform>\n <PackageCode>UA</PackageCode>\n </data>\n </GetPackage>\n </soap12:Body>\n</soap12:Envelope>"
let postData = parameters.data(using: .utf8)
var request = URLRequest(url: URL(string: "https://www.cool-english.info/Service.asmx?wsdl")!,timeoutInterval: Double.infinity)
request.addValue("application/soap+xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = postData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
print(String(describing: error))
return
}
let parser = XMLParser(data: data)
parser.delegate = self
parser.parse()
semaphore.signal()
}
task.resume()
semaphore.wait()
}
// XML解析委托
func parser(_ parser: XMLParser, foundCharacters string: String) {
let data = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
if (!data.isEmpty) {
if currentParsingElement == "GetPackageResult" {
packageResult += data
self.saveBase64StringToAudio(packageResult)
}
}
}
//用于在文档目录中写入
func saveBase64StringToAudio(_ base64String: String) {
guard
var documentsURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last,
let convertedData = Data(base64Encoded: base64String)
else {
//handle error when getting documents URL
return
}
//name your file however you prefer0
documentsURL.appendPathComponent("audio.mp3")
do {
try convertedData.write(to: documentsURL)
do {
audioPlayer = try AVAudioPlayer(contentsOf: documentsURL)
guard let player = audioPlayer else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
} catch {
//handle write error here
}
print(documentsURL)
}