我正在尝试将录制的视频转换为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()
}
你在String
混合了Data
和createBodyWithParams
不管怎样,不要在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)
}