无法将'__ NSCFString'类型的值转换为'NSData'

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了无法将'__ NSCFString'类型的值转换为'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)
")
                body.appendString("Content-Disposition: form-data; name="(key)"

")
                body.appendString("(value)
")
            }
        }
        var filename = ""

        if imageSelected == true {
            filename = "video-(uuid).mp4"
        }


        let mimetype = "video/mp4"
        body.append("--(boundary)
".data(using: String.Encoding.utf8)!)
        body.appendString("Content-Disposition: form-data; name="(filePathKey!)"; filename="(filename)"
")
        body.appendString(String(describing: "Content-Type: (mimetype)

".data(using: String.Encoding.utf8)))
        body.append(mediaPath)
        body.append(String(format: "
").data(using: String.Encoding.utf8)!)

        body.append("--(boundary)--
".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混合了DatacreateBodyWithParams

不管怎样,不要在Swift 3+中使用NSMutableDataDatavar可变

但是我建议将身体组成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)
"
            body += "Content-Disposition: form-data; name="(key)"

"
            body += "(value)
"
        }
    }
    var filename = ""

    if imageSelected {
        filename = "video-(uuid).mp4"
    }

    let mimetype = "video/mp4"
    body += "--(boundary)
"
    body += "Content-Disposition: form-data; name="(filePathKey!)"; filename="(filename)"
"
    body += "Content-Type: (mimetype)

"
    body += String(data: mediaPath, encoding: .utf8)!
    body += "
"

    body += "--(boundary)--
"

    return Data(body.utf8)

}

以上是关于无法将'__ NSCFString'类型的值转换为'NSData'的主要内容,如果未能解决你的问题,请参考以下文章

[__NSCFString name]:发送到实例的无法识别的选择器

[__NSCFString objectAtIndex:]:无法识别的选择器发送到实例错误

如何解决此错误:无法将类型“__NSCFString”(0x10354a248)的值转换为“UIImage”(0x104c42b48)

__NSCFString setHidden:无法识别的选择器发送到实例

斯威夫特:无法将“无法将“__NSCFString”(0x10e4d5ef0)类型的值转换为“NSDictionary”(0x10e4d6bc0)类型的值。

如何解决 [__NSCFString _isResizable] 的运行时错误:无法识别的选择器发送到实例?