在后台

时间:2015-05-21 10:09:22

标签: ios objective-c iphone ipad

嗨在我的应用程序中,我需要通过将UIImage编码为Base64string来在后台上传多个图像。请让我知道如何继续做同样的事情或建议我一些更好的方法。

无论如何都要提前感谢。

此致 Tapash

2 个答案:

答案 0 :(得分:0)

注意:参见编辑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
    }
}

答案 1 :(得分:0)

最后我实施了。程序如下。我要求每个人在需要时修改这个并提出更有效的方法:

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)")

            }
        })
    } 
}