我试图将视频上传到我的服务器。 我从相册中选择视频,但“致命错误:意外地发现零,同时展开可选值”。Swift上传视频到Http服务器?
请找到下面的代码以获取更多信息。
let videoURL: String = NSBundle.mainBundle().pathForResource("IMG_2859", ofType: "MOV")!
// var videoData: NSData = NSData.dataWithContentsOfURL(NSURL.fileURLWithPath(videoURL))!
print(videoURL)
let data = NSData(contentsOfFile: videoURL)
print(data)
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest()
print(session)
print(request)
request.URL = NSURL(string: "uploadvideo/uploadtoserver?user_email=\(candit_email)")
print(request.URL)
request.HTTPMethod = "POST"
let boundary = "------------------------8744f963ff229392"
request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let postData = NSMutableData()
postData.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
print("Upload Video File1")
postData.appendData("Content-Disposition: form-data; name=\"filedata\"; filename=\"MOV\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
print("Upload Video File2")
postData.appendData("Content-Type: video/x-msvideo\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
print("Upload Video File3")
postData.appendData(NSData(data: data!))
print("Upload Video File4")
postData.appendData("\r\n--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
print("Upload Video File5")
request.HTTPBody = postData
print("Upload Video File6")
print(request.HTTPBody)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
let error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
do{
if let jsonResult: NSDictionary! = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as? NSDictionary{
}
} catch let error as NSError {
print(error.localizedDescription)
}
})
}
我在下面提到了这两个链接,但对我没用。
1)Imageor-video-posting-to-server-in-swift
2)how-to-upload-video-to-server-from-iphone
尝试使用Alamofire,这是一个容易得多。如果您需要传递参数,请参阅[this](https://github.com/Alamofire/Alamofire/issues/1004)。 –
对不起后期重播....我尝试Alamofire但在此行之后显示空错误让“videoURL:String = NSBundle.mainBundle()。pathForResource(”IMG_2859“,ofType:”MOV“)!” – Manikandaprabu
这个'IMG_2859'在哪里?你的资产?如果是这种情况,您应该使用'UIImageJPEGRepresentation'上传它,因为您的资产将在编译时打包。检查我给你的链接。 –