【发布时间】:2016-06-09 07:43:07
【问题描述】:
我正在尝试将视频上传到我的服务器。 我从相册中选择视频,但“致命错误:在展开可选值时意外发现 nil”。
请查看以下代码以获取更多信息。
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。
-
抱歉延迟重播...... !”
-
这是哪里的
IMG_2859?你的资产?如果是这种情况,您应该使用UIImageJPEGRepresentation上传它,因为您的资产将在编译时打包。检查我上面给你的链接。 -
相册中的IMG_2859视频->相机胶卷
-
您不能以这种方式访问不在您项目中的资源。你知道用户的照片库恰好有你需要的图像是没有意义的。
标签: ios swift ios9 nsurlsession