【问题标题】:image uploading in background后台上传图片
【发布时间】:2015-05-21 10:09:21
【问题描述】:

您好,在我的应用程序中,我需要通过将 UIImage 编码为 Base64string 来在后台上传多张图片。请让我知道如何继续执行相同操作或建议我一些更好的方法。

无论如何提前谢谢。

问候 塔帕什

【问题讨论】:

  • 为什么要对图像进行编码...
  • 您要一张一张地上传图片还是一次全部上传?

标签: ios objective-c iphone ipad


【解决方案1】:

注意:见编辑 1

你可以试试

NSArray* images = // Get your images
[self performSelectorInBackground:@selector(uploadImages:) withObject:images];

...

- (void)uploadImages:(NSArray*)images {
    // Encode images and upload them...
}

performSelectorInBackground:withObject 在后台线程中执行该方法。该方法,在本例中为 uploadImages:,应在同一类中定义(或委托给 Util 类或类似类)。

编辑 1

正如@user1963877 所说,performSelectorInBackground:withObject 已过时,正在逐渐被GCD 取代,因此不应再使用它。使用dispatch_async(),您可以重现相同的行为,如下所示:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
    // Encode images and upload them, you are in a background thread...
    dispatch_async(dispatch_get_main_queue(), ^{
        // Do whatever in UI, you are in UI thread
    }
}

【讨论】:

  • performSelectorInBackground 自 GCD 引入以来已过时。最好使用dispatch_async
  • @user1963877 查看我的编辑,如果可以,您可以撤消否决票
  • 感谢您的回答。请告诉我,当我的应用在使用 GCD 上传图片时进入后台时会发生什么。
  • 您没有在问题中指定应用程序本身将进入后台,而只是线程。看看stackoverflow.com/a/9812176/1357853
【解决方案2】:

我终于实现了。程序如下。我要求大家根据需要修改此内容并提出更有效的方法:

typealias PLMImageUploadCompletionHandler = (AnyObject?, Int, NSError?) -> Void

class ImageUploader: NSObject {
    static let sharedInstance = ImageUploader()
    private override init() {} //This prevents others from using the default '()' initializer for this class.

    //MARK:- Api Calls
    func uploadImageWithAlamofire(selectedImages: Array<Image> , completionHandler :@escaping PLMImageUploadCompletionHandler)
    {
        //***** Added By Priti ***********////

        let username = "test"
        let password = "XXX122"
        let loginString = String(format: "%@:%@", username, password)

        let headers:HTTPHeaders = [
            "Authorization": "Basic \(loginString.data(using: String.Encoding.utf8)!.base64EncodedString())"
        ]

        let imageServiceURl = URL(string:"your url")

        let postParams:[String: Any] = [            
            "fileName":String(describing: fileArray),
            "objectID":String(describing: objectID),
            "comments":String(describing: commentsArray),
            "objectType":String(describing: objectType),
            "uniqueId":String(describing: arrIDs),
            "location":String(describing: locationArray)
        ]

        print(fileArray)

        Alamofire.upload(multipartFormData: { multipartFormData in
            for (key, value) in postParams
            {
                multipartFormData.append(((value as AnyObject).data(using:String.Encoding.utf8.rawValue))!, withName: key)
            }
            for i in 0..<selectedImages.count {
                let data = UIImageJPEGRepresentation(selectedImages[i].value(forKey: "image") as! UIImage,0.6)
                multipartFormData.append(data!, withName: "uploadedFiles", fileName: "image\(i).png", mimeType: "image/png")
            }
        },to:imageServiceURl!, method: .post, headers:headers,
          encodingCompletion: { encodingResult in

            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseJSON {
                    response in
                    switch response.result
                    {
                        case.success:
                            print(response.request!)  // original URL request
                            print(response.response!) // URL response
                            print(response.data!)     // server data
                            print(response.result)   // result of response serialization
                            // Post notification
                            DispatchQueue.main.async( execute: {
                                completionHandler(nil, HttpStatusType.OK_STATUS. rawValue, nil)
                            })
                        break

                        case.failure(let error):
                                completionHandler(nil, HttpStatusType.HTTP_ERROR. rawValue, error as NSError)
                        break
                    }
                }
            case .failure(let encodingError):
                print("error:\(encodingError)")

            }
        })
    } 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-08
    相关资源
    最近更新 更多