我正在尝试上传用户从其相册中选择的图像,并保持上传它们,即使用户将我的应用程序置于后台/挂起状态,然后开始使用其他应用程序。但是,除了图像外,我还想在httpBody中发送一些字典参数(如"Pro_Id"),以多部分上传方式保存图像。来源链接:Background upload multiple images using single NSURLSession uploadTaskWithRequest">Background upload multiple images using single NSURLSession uploadTaskWithRequest。我已按以下方式执行回答中的操作:要在后台会话中上传数据,必须首先将数据保存到文件中。
我应该收到一个上传成功的消息,但是反而收到了错误消息,提示请求中请指定“pro_ID”。
我的实现有问题吗? 其他iOS应用程序如何在后台上传图像?它们也必须发送一些数据,以告诉图像属于后端中的哪个对象?
- 使用writeToFile:options:将数据保存到文件中。
- 调用NSURLSession uploadTaskWithRequest:fromFile:来创建任务。请注意,请求中不能包含HTTPBody中的数据,否则上传将失败。
- 在URLSession:didCompleteWithError:委托方法中处理完成。
- 您可能还希望处理在应用程序处于后台时完成的上传。
实现以下内容: 1. 在AppDelegate中实现application:handleEventsForBackgroundURLSession:completionHandler方法。 2. 使用提供的标识符创建一个NSURLSession。 3. 像通常的上传一样响应代理方法(例如,在URLSession:didCompleteWithError:中处理响应)。 4. 在完成事件处理后调用URLSessionDidFinishEventsForBackgroundURLSession方法。
struct Media {
let key: String
let filename: String
let data: Data
let mimeType: String
init?(withImage image: UIImage, forKey key: String) {
self.key = key
self.mimeType = "image/jpeg"
self.filename = "kyleleeheadiconimage234567.jpg"
guard let data = image.jpegData(compressionQuality: 0.7) else { return nil }
self.data = data
}
}
@IBAction func postRequest(_ sender: Any) {
let uploadURL: String = "http://abc.xyz.com/myapi/v24/uploadimageapi/sessionID?rtype=json"
let imageParams = [
"isEdit":"1",
"Pro_Id":"X86436",
"Profileid":"c0b7b9486b9257041979e6a45",
"Type":"MY_PLAN",
"Cover":"Y"]
guard let mediaImage = Media(withImage: UIImage(named: "5MB")!, forKey: "image") else { return }
let imageData = mediaImage.data
let randomFilename = "myImage"
let fullPath = getDocumentsDirectory().appendingPathComponent(randomFilename)
do {
let data = try NSKeyedArchiver.archivedData(withRootObject: imageData, requiringSecureCoding: false)
try data.write(to: fullPath)
} catch {
print("Couldn't write file")
}
guard let url = URL(string: uploadURL) else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
let boundary = generateBoundary()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.addValue("Client-ID f65203f7020dddc", forHTTPHeaderField: "Authorization")
request.addValue("12.2", forHTTPHeaderField: "OSVersion")
request.addValue("keep-alive", forHTTPHeaderField: "Connection")
let dataBody = createDataBody(withParameters: imageParams, media: nil, boundary: boundary)
request.httpBody = dataBody
ImageUploadManager.shared.imageUploadBackgroundTask = UIApplication.shared.beginBackgroundTask {
print(UIApplication.shared.backgroundTimeRemaining)
// upon completion, we make sure to clean the background task's status
UIApplication.shared.endBackgroundTask(ImageUploadManager.shared.imageUploadBackgroundTask!)
ImageUploadManager.shared.imageUploadBackgroundTask = UIBackgroundTaskIdentifier.invalid
}
let session = ImageUploadManager.shared.urlSession
session.uploadTask(with: request, fromFile: fullPath).resume()
}
func generateBoundary() -> String {
return "Boundary-\(NSUUID().uuidString)"
}
func createDataBody(withParameters params: Parameters?, media: [Media]?, boundary: String) -> Data {
let lineBreak = "\r\n"
var body = Data()
if let parameters = params {
for (key, value) in parameters {
body.append("--\(boundary + lineBreak)")
body.append("Content-Disposition: form-data; name=\"\(key)\"\(lineBreak + lineBreak)")
body.append("\(value + lineBreak)")
}
}
if let media = media {
for photo in media {
body.append("--\(boundary + lineBreak)")
body.append("Content-Disposition: form-data; name=\"\(photo.key)\"; filename=\"\(photo.filename)\"\(lineBreak)")
body.append("Content-Type: \(photo.mimeType + lineBreak + lineBreak)")
body.append(photo.data)
body.append(lineBreak)
}
}
body.append("--\(boundary)--\(lineBreak)")
return body
}
class ImageUploadManager: NSObject, URLSessionDownloadDelegate {
static var shared: ImageUploadManager = ImageUploadManager()
var imageUploadBackgroundTask: UIBackgroundTaskIdentifier?
private override init() { super.init()}
lazy var urlSession: URLSession = {
let config = URLSessionConfiguration.background(withIdentifier: " ***My-Background-Upload-Session-********* ")
config.isDiscretionary = true
config.sessionSendsLaunchEvents = true
config.isDiscretionary = false
return URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue())//nil)
}()
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if totalBytesExpectedToWrite > 0 {
let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
print("Progress \(downloadTask) \(progress)")
}
}
//first this method gets called after the call coming to appDelegate's handleEventsForBackgroundURLSession method, then moves to didCompleteWithError
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
print("************* Download finished ************* : \(location)")
try? FileManager.default.removeItem(at: location)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
print("************* Task completed ************* : \n\n\n \(task), error: \(error) \n************\n\n\n")
UIApplication.shared.endBackgroundTask(self.imageUploadBackgroundTask!)
self.imageUploadBackgroundTask = UIBackgroundTaskIdentifier.invalid
print(task.response)
if error == nil{
}else{
}
}
}
我应该收到一个上传成功的消息,但是反而收到了错误消息,提示请求中请指定“pro_ID”。
我的实现有问题吗? 其他iOS应用程序如何在后台上传图像?它们也必须发送一些数据,以告诉图像属于后端中的哪个对象?