- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想添加一个进度条以准确了解我的视频上传的百分比,但无法调用 didCompleteWithError、didReceive 响应、didSendBodyData bytesSent:Int64、totalBytesSent:Int64、totalB 等...
我加好了delegate,但是没能抓到问题。
@objcMembers open class DAL : NSObject
{
var response: URLResponse?
var session: URLSession?
var uploadTask: URLSessionUploadTask?
let opQueue = OperationQueue()
static let sharedInstance = DAL()
fileprivate let showLogs = true
var WSURL:String = SERVER_PROTOCOL + DOMAIN_NAME_ADDRESS //"http://localhost:3000"
var eventKey:String = EVENT_TO_USE
}
在另一个类中:
extension DAL: URLSessionDelegate,URLSessionDataDelegate, URLSessionTaskDelegate
{
func uploadVideo(_ videoPath: String, fileName: String, eventId: Int, contactId: Int, type: Int, callback: @escaping (_ data:Data?, _ resp:HTTPURLResponse?, _ error:NSError?) -> Void)
{
// let filePath = video
// let videoFileURL = NSURL(fileURLWithPath: videoPath)
var video_data: NSData?
do {
video_data = try NSData(contentsOfFile: (videoPath), options: NSData.ReadingOptions.alwaysMapped)
} catch _ {
video_data = nil
return
}
let WSURL:String = "https://" + "ren.newp.fr/node"
let requestURLString = "\(WSURL)/regtions/lead/photo//"
let url = URL(string: requestURLString)
#if DEBUG
print(requestURLString)
#endif
let request = NSMutableURLRequest(url: url!)
request.httpMethod = "POST"
let boundary = generateBoundaryString()
//define the multipart request type
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let body = NSMutableData()
let mimetype = "video/mp4"
//define the data post parameter
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition:form-data; name=\"eventId\"\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append("\(eventId)\r\n".data(using: String.Encoding.utf8)!)
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition:form-data; name=\"contactId\"\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append("\(contactId)\r\n".data(using: String.Encoding.utf8)!)
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition:form-data; name=\"type\"\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append("\(type)\r\n".data(using: String.Encoding.utf8)!)
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition:form-data; name=\"file\"; filename=\"\(fileName)\"\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append(video_data! as Data)
body.append("\r\n".data(using: String.Encoding.utf8)!)
body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)
request.httpBody = body as Data
request.setValue("Keep-Alive", forHTTPHeaderField: "Connection")
let config = URLSessionConfiguration.default
self.session = URLSession(configuration: config, delegate: self, delegateQueue: self.opQueue)
let fileUrl = URL(string:"\(videoPath)/\(fileName)")
if let task = session?.uploadTask(with: request as URLRequest, from: video_data! as Data){
task.resume()}
}
private func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
// the task finished
if let err = error {
print("Error: \(err.localizedDescription)")
} else {
print("The upload was successful.")
self.session?.finishTasksAndInvalidate()
} // end if
} // end func
private func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
print("did receive response")
self.response = response
print(self.response!)
completionHandler(URLSession.ResponseDisposition.allow)
} // end func
private func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
let progress = Float(totalBytesSent) / Float(totalBytesExpectedToSend)
print(progress)
} // end func
public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
}
func generateBoundaryString() -> String
{
return "Boundary-\(UUID().uuidString)"
}
}
}
提前致谢
最佳答案
从您的类中删除开放参数: https://stackoverflow.com/a/38950955
简而言之:(来自其他帖子)
An open class is accessible and subclassable outside of the defining module. An open class member is accessible and overridable outside of the defining module.
A public class is accessible but not subclassable outside of the defining module. A public class member is accessible but not overridable outside of the defining module.
关于iOS:didCompleteWithError、didReceive 响应未通过 URLSession.uploadTask 触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53710141/
我正在与 NSURLSession 上传和下载作斗争,如果不是因为例如在发送(上传)100 个文件的背景下,一切似乎都有效: - (void)URLSession:(NSURLSession *)se
在 IOS9 应用程序上工作,该应用程序在作为 NSURLSessionDelegate 的 Controller 中执行后台 URLSession。这是我如何开始的: self.sessio
当我通过按下电源按钮强制我的设备进入休眠模式时,我的后台任务通过调用委托(delegate)方法 didCompleteWithError 停止并出现错误: The operation couldn’
我想在我的服务器上尝试一个 post 调用直到成功,我想每 30 秒尝试一次。 所以我在调用时使用 NSURLSession: NSURLSessionDownloadTask *task = [s
我有一个符合用于下载数据的 NSURLSession 委托(delegate)的类,当完成调用方法 func URLSession(session: NSURLSession, task: NSURL
我有以下 NSURLSession 的实现. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration default
我想添加一个进度条以准确了解我的视频上传的百分比,但无法调用 didCompleteWithError、didReceive 响应、didSendBodyData bytesSent:Int64、to
场景是在上传过程中多次将app调到后台和前台,调用didCompleteWithError:方法调到前台时error参数为null。概率是 1/3。 由于错误参数没有提供任何信息,我如何找出问题所在。
我所有的网络代码都依赖于 NSURLSession 委托(delegate)方法——而不是完成处理程序。我的数据和下载任务都很好,但我的上传任务从来没有导致URLSession:task:didCom
我是一名优秀的程序员,十分优秀!