当 iOS 应用程序在后台时使用 POST-API 上传图像

pra*_*vir 6 post multipartform-data image-uploading ios swift

我正在尝试上传用户从他们的图库中选择的图像,然后继续上传它们,即使用户将我的应用程序置于后台/挂起状态,然后开始使用其他一些应用程序。

但是,除了图像,我想在请求的 httpBody(如“Pro_Id”)中发送一些字典参数,以保持图像的分段上传

后台使用单个 NSURLSession uploadTaskWithRequest 上传多张图片

我已经完成了以下使用单个 NSURLSession uploadTaskWithRequest 后台上传多个图像中的回答 :

要在后台会话中上传,必须先将数据保存到文件中。

  1. 使用 writeToFile:options: 将数据保存到文件。
  2. 调用 NSURLSession uploadTaskWithRequest:fromFile: 创建任务。请注意,请求不得包含 HTTPBody 中的数据,否则上传将失败。
  3. 在 URLSession:didCompleteWithError: 委托方法中处理完成。
  4. 您可能还想处理在应用程序处于后台时完成的上传。

在 AppDelegate 中实现 1. 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{
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

我应该收到一条成功消息,说明该图片已上传,但我收到了错误消息作为响应,说请在请求中指定“pro_ID”。

我的实现有什么问题吗?而且,其他 ios 应用程序如何在后台上传图像,它们也必须发送一些数据来告诉该图像属于后端的哪个对象?

小智 2

我不认为我们可以添加 httpbody,您可能必须使用查询参数发送数据,就像我们发送 GET 请求一样,然后在服务器上(如果您使用 PHP)使用 $_GET['Your_Id'] 来访问该 id