当 iOS 应用程序处于后台时使用 POST-API 上传图片
image upload using POST-API when iOS app is in background
我正在尝试上传用户从他们的图库中选择的图片,然后继续上传它们,即使用户将我的应用程序置于 background/suspended 状态然后开始使用其他应用程序也是如此。
但是,我想连同图像一起在请求的 httpBody 中发送一些字典参数(如 "Pro_Id"),以将图像保持在分段上传中
我已经完成了以下的回答
:
要在后台会话中上传,必须先将数据保存到文件中。
- 使用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 应用程序如何在后台上传图像,它们也必须发送一些数据来告知该图像属于后端中的哪个对象?
启用后台模式上传图片。
我认为我们不能添加 httpbody,您可能必须使用查询参数发送数据,就像我们在 GET 请求中发送的那样,然后如果您的请求在 PHP 中,则在服务器上使用 $_GET['Your_Id'] 访问那个 id
我正在尝试上传用户从他们的图库中选择的图片,然后继续上传它们,即使用户将我的应用程序置于 background/suspended 状态然后开始使用其他应用程序也是如此。
但是,我想连同图像一起在请求的 httpBody 中发送一些字典参数(如 "Pro_Id"),以将图像保持在分段上传中
我已经完成了以下的回答
要在后台会话中上传,必须先将数据保存到文件中。
- 使用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 应用程序如何在后台上传图像,它们也必须发送一些数据来告知该图像属于后端中的哪个对象?
启用后台模式上传图片。
我认为我们不能添加 httpbody,您可能必须使用查询参数发送数据,就像我们在 GET 请求中发送的那样,然后如果您的请求在 PHP 中,则在服务器上使用 $_GET['Your_Id'] 访问那个 id