7

我创建了一个小型演示应用程序,应用程序使用 UIImagePickerController 从 iPhone 访问图像和视频。当我选择任何图像或视频时,应用程序会在文档目录中创建它的副本(图像或视频)。并使用 GCDWebserver 在 iPhone 上创建 Web 服务器,并需要公开选定的图像或视频。但它不起作用。

这是示例代码,不确定我可能错在哪里。

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet weak var btnselect: UIButton!
let videoPicker = UIImagePickerController()

@IBAction func btnSelect(_ sender: Any) {

        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
            let myPickerController = UIImagePickerController()
            myPickerController.delegate = self;
            myPickerController.sourceType = .photoLibrary
            myPickerController.allowsEditing = false
            self.present(myPickerController, animated: true, completion: nil)
        }

    }

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        self.dismiss(animated: true, completion: nil)
    }

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

    // 1. saving video to documents directory

      let videoURL = info[UIImagePickerController.InfoKey.mediaURL] as! NSURL
            let videoData = NSData(contentsOf: videoURL as URL)
            let path = try! FileManager.default.url(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask, appropriateFor: nil, create: false)

            let newPath = path.appendingPathComponent("/myTestVideo.mp4")
            do {
                try videoData?.write(to: newPath)
            } catch {
                print(error)
            }


 // 2. Create web server on iPhone using GCDWebServer

        let webServer = GCDWebServer()
        webServer.addDefaultHandler(forMethod: "GET", request: GCDWebServerRequest.self, processBlock: {request in
        return GCDWebServerDataResponse(newPath)

       })
       webServer.start(withPort: 8080, bonjourName: "GCD Web Server")

}
}

我需要此 GCD Web 服务器托管/访问此选定的(图像或视频)。

4

2 回答 2

1

您可以使用 GCDWebServerDataResponse 将文件作为响应传递,如下所示:

webServer!.addDefaultHandler(forMethod: "GET", request: GCDWebServerRequest.self, processBlock: {request in
    let path = Bundle.main.path(forResource: "sample", ofType: "mp4")
    let handler = FileHandle.init(forReadingAtPath: path!)
    return GCDWebServerDataResponse(data: (handler?.readDataToEndOfFile())!, contentType: "video/mp4")  
})

请注意,当您需要提供文件的内容类型和数据时。

于 2019-12-05T19:03:06.980 回答
0

Assuming it could be according wrong path

let newPath = path.appendingPathComponent("/myTestVideo.mp4")

producing ..../Documents//myTestVideo.mp4

Try to remove backslash from appending path component.

let newPath = path.appendingPathComponent("myTestVideo.mp4")

Also there is small chance that the problem could be related to "file://" prefix. If previous suggestion will not help try to remove prefix.

于 2019-05-29T07:52:05.377 回答