无法将类型“__NSCFString”的值转换为 'NSData'
Could not cast value of type '__NSCFString' to 'NSData'
我正在尝试将录制的视频转换为 mp4,然后将其上传到我的服务器。我 运行 遇到了转换值的问题,并到处寻找解决方案。该应用程序在某个时刻崩溃,我继续收到“无法将类型‘__NSCFString”的值转换为 'NSData' 错误。感谢任何帮助。
let time = endDate.timeIntervalSince(startDate)
print(time)
print("Successful!")
print(exportSession?.outputURL as Any)
let mediaPath = exportSession?.outputURL?.path as NSString!
self.uploadVideo(mediaPath as! Data)
// 上传视频
func uploadVideo(_ mediaPath: Data) {
func createBodyWithParams(_ parameters: [String: String]?, filePathKey: String?, mediaPath: Data, boundary: String) -> Data {
let body = NSMutableData();
if parameters != nil {
for (key, value) in parameters! {
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
}
var filename = ""
if imageSelected == true {
filename = "video-\(uuid).mp4"
}
let mimetype = "video/mp4"
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString(String(describing: "Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8)))
body.append(mediaPath)
body.append(String(format: "\r\n").data(using: String.Encoding.utf8)!)
body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)
return body as Data
}
let id = user!["id"] as! String
uuid = UUID().uuidString
let url = URL(string: "http://www.foo.com/videoposts.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let param = [
"id" : id,
"uuid" : uuid
]
print("just passed videopost page")
// body
let boundary = "Boundary-\(UUID().uuidString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
// if picture is selected, compress it by half
//let imageData = Data()
// ... body
request.httpBody = createBodyWithParams(param, filePathKey: "filename", mediaPath: AnyObject, boundary: boundary)
// launch session
URLSession.shared.dataTask(with: request) { data, response, error in
// get main queu to communicate back to user
DispatchQueue.main.async(execute: {
if error == nil {
do {
// json containes $returnArray from php
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
// declare new var to store json inf
guard let parseJSON = json else {
print("Error while parsing")
return
}
// get message from $returnArray["message"]
let message = parseJSON["message"]
// if there is some message - post is made
if message != nil {
// reset UI
self.postBtn.alpha = 0.4
self.imageSelected = false
// switch to another scene
self.tabBarController?.selectedIndex = 4
}
} catch {
// get main queue to communicate back to user
DispatchQueue.main.async(execute: {
let message = "\(error)"
appDelegate.infoView(message: message, color: colorSmoothRed)
})
return
}
} else {
// get main queue to communicate back to user
DispatchQueue.main.async(execute: {
let message = error!.localizedDescription
appDelegate.infoView(message: message, color: colorSmoothRed)
})
return
}
})
}.resume()
}
您在 createBodyWithParams
中混淆了 String
和 Data
无论如何不要在 Swift 3+ 中使用 NSMutableData
。 Data
与 var
可变
但是我建议将正文组合为 String
并在末尾创建 Data
对象。
func createBodyWithParams(_ parameters: [String: String]?, filePathKey: String?, mediaPath: Data, boundary: String) -> Data {
var body = ""
if let params = parameters {
for (key, value) in params {
body += "--\(boundary)\r\n"
body += "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n"
body += "\(value)\r\n"
}
}
var filename = ""
if imageSelected {
filename = "video-\(uuid).mp4"
}
let mimetype = "video/mp4"
body += "--\(boundary)\r\n"
body += "Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n"
body += "Content-Type: \(mimetype)\r\n\r\n"
body += String(data: mediaPath, encoding: .utf8)!
body += "\r\n"
body += "--\(boundary)--\r\n"
return Data(body.utf8)
}
我正在尝试将录制的视频转换为 mp4,然后将其上传到我的服务器。我 运行 遇到了转换值的问题,并到处寻找解决方案。该应用程序在某个时刻崩溃,我继续收到“无法将类型‘__NSCFString”的值转换为 'NSData' 错误。感谢任何帮助。
let time = endDate.timeIntervalSince(startDate)
print(time)
print("Successful!")
print(exportSession?.outputURL as Any)
let mediaPath = exportSession?.outputURL?.path as NSString!
self.uploadVideo(mediaPath as! Data)
// 上传视频
func uploadVideo(_ mediaPath: Data) {
func createBodyWithParams(_ parameters: [String: String]?, filePathKey: String?, mediaPath: Data, boundary: String) -> Data {
let body = NSMutableData();
if parameters != nil {
for (key, value) in parameters! {
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
}
var filename = ""
if imageSelected == true {
filename = "video-\(uuid).mp4"
}
let mimetype = "video/mp4"
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString(String(describing: "Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8)))
body.append(mediaPath)
body.append(String(format: "\r\n").data(using: String.Encoding.utf8)!)
body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)
return body as Data
}
let id = user!["id"] as! String
uuid = UUID().uuidString
let url = URL(string: "http://www.foo.com/videoposts.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let param = [
"id" : id,
"uuid" : uuid
]
print("just passed videopost page")
// body
let boundary = "Boundary-\(UUID().uuidString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
// if picture is selected, compress it by half
//let imageData = Data()
// ... body
request.httpBody = createBodyWithParams(param, filePathKey: "filename", mediaPath: AnyObject, boundary: boundary)
// launch session
URLSession.shared.dataTask(with: request) { data, response, error in
// get main queu to communicate back to user
DispatchQueue.main.async(execute: {
if error == nil {
do {
// json containes $returnArray from php
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
// declare new var to store json inf
guard let parseJSON = json else {
print("Error while parsing")
return
}
// get message from $returnArray["message"]
let message = parseJSON["message"]
// if there is some message - post is made
if message != nil {
// reset UI
self.postBtn.alpha = 0.4
self.imageSelected = false
// switch to another scene
self.tabBarController?.selectedIndex = 4
}
} catch {
// get main queue to communicate back to user
DispatchQueue.main.async(execute: {
let message = "\(error)"
appDelegate.infoView(message: message, color: colorSmoothRed)
})
return
}
} else {
// get main queue to communicate back to user
DispatchQueue.main.async(execute: {
let message = error!.localizedDescription
appDelegate.infoView(message: message, color: colorSmoothRed)
})
return
}
})
}.resume()
}
您在 createBodyWithParams
String
和 Data
无论如何不要在 Swift 3+ 中使用 NSMutableData
。 Data
与 var
但是我建议将正文组合为 String
并在末尾创建 Data
对象。
func createBodyWithParams(_ parameters: [String: String]?, filePathKey: String?, mediaPath: Data, boundary: String) -> Data {
var body = ""
if let params = parameters {
for (key, value) in params {
body += "--\(boundary)\r\n"
body += "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n"
body += "\(value)\r\n"
}
}
var filename = ""
if imageSelected {
filename = "video-\(uuid).mp4"
}
let mimetype = "video/mp4"
body += "--\(boundary)\r\n"
body += "Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n"
body += "Content-Type: \(mimetype)\r\n\r\n"
body += String(data: mediaPath, encoding: .utf8)!
body += "\r\n"
body += "--\(boundary)--\r\n"
return Data(body.utf8)
}