Загрузка изображения по методу Alamofire.upload в swift4 - PullRequest
0 голосов
/ 25 октября 2018

Мне нужно загрузить изображение, используя метод Alamofire.upload(multipartFormData.Мой код указан ниже, но я получаю сообщение об ошибке, подобное этому:

FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error
 Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character
 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))

Может кто-нибудь сказать мне, как решить проблему?

func photoSave(_ photoImage : UIImage, type : String)
{
    let urlString = ServerUrl + "document_upload"
    let imageUpload = UIImageJPEGRepresentation(photoImage, 0.5)        
    Alamofire.upload(multipartFormData: { (multipartFormData) in
        let date = Date().timeIntervalSince1970 * 1000
        let fileName = String(date) + "Image.jpg"
        multipartFormData.append(imageUpload!, withName: "image", fileName: fileName, mimeType: "image/jpg")
        multipartFormData.append((self.token.data(using: String.Encoding.utf8, allowLossyConversion: false)!), withName: "token")
        multipartFormData.append((type.data(using: String.Encoding.utf8, allowLossyConversion: false))!, withName: "document_type")
    }, to: urlString, method: .post, encodingCompletion: { (result) in
        switch result {
        case .success(let upload, _, _):
            upload.responseJSON { response in
                print("response11 : ", response.request?.url! as Any,response)
                if response.result.isSuccess
                {
                    let result : AnyObject = response.result.value as AnyObject

                    let success = result["status_message"] as? String

                    if success == "Image Upload Successfully"
                    {
                        DispatchQueue.main.async
                            {                                 
                        }
                    }
                    else
                    {
                        let msg = result["status_message"] as? String
                        DispatchQueue.main.async
                            {
                                let alert = UIAlertController(title: msg, message: "", preferredStyle: .alert)
                                let ok = UIAlertAction(title: "OK", style: .cancel, handler: { Void in
                                })
                                alert.addAction(ok)
                                self.present(alert, animated: true, completion: nil)
                                return
                        }
                    }
                }
                else
                {
                    DispatchQueue.main.async
                        {
                            let alert = UIAlertController(title: "Network Connection Lost", message: "Please try again", preferredStyle: .alert)
                            let ok = UIAlertAction(title: "OK", style: .cancel, handler: { Void in
                            })
                            alert.addAction(ok)
                            self.present(alert, animated: true, completion: nil)
                    }
                    return
                }
            }
        case .failure(let encodingError):
            print(encodingError)
        }
    })
}

Ответы [ 2 ]

0 голосов
/ 25 октября 2018

Попробуйте, это сработало для меня.

func requestAPIWithImage( parameters:  Parameters,url: URLConvertible,Completion: @escaping (_ success: Bool,_ response: AnyObject) -> Void) {
    Alamofire.upload(multipartFormData: { (multipartFormData) in
        print(parameters)
        if Array(parameters.keys).contains(Keys.Image) {
        multipartFormData.append(UIImageJPEGRepresentation((parameters)[Keys.Image] as! UIImage, 1)!, withName: "image", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
        }
        for (key, value) in parameters {
            print(key,value)
            if key != Keys.Image{
            multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
            }
        }
    }, to:url)
    { (result) in
        switch result {
        case .success(let upload, _, _):
            upload.uploadProgress(closure: { (progress) in
            })
            upload.responseJSON { response in
                print(response.result)
                self.getValidDict(result: response.result, completion: { (dict, error) in
                    var dict = dict
                    if dict == nil {
                        dict = NSDictionary.init(dictionary:
                            [kBaseMessageKey: error?.localizedDescription ?? "Some error has been occured",
                             kBaseStatusKey: false])
                    }
                       Completion(true,dict![Keys.result]! as AnyObject)
                })
           }
        case .failure(let encodingError):
            Completion(false,encodingError.localizedDescription as AnyObject)
            break
        }
    }
}
0 голосов
/ 25 октября 2018

Swift 4

Попробуйте этот метод (КОПИЯ ПАСТЫ из рабочего проекта), он должен работать с вами.

func makeMultipartRequest(endPoint: String, parameters: [String:String], image: UIImage, add_headers: Bool = true, completion: @escaping (_ : Any) -> Void)
{
    var headers: [String:String]? = nil

    if add_headers
    {
        headers =
        [
            "Authorization" : LoginModel.instance.userToken,
            "Content-type": "multipart/form-data",
            "Accept": "application/json"
        ]
    }

    print(headers ?? "no headers")

    Alamofire.upload(multipartFormData: { multipartFormData in

        // image in our API have key : thePhoto

        //
        // resize image first
        //

        var tempImage = image

        // 1) pick the largest of width or height
        // 2) if the largest > 1280 then resize the image
        // (respect to aspect ratio)

        if tempImage.size.width > tempImage.size.height
        {
            if tempImage.size.width > 1280.0
            {
                tempImage = tempImage.resizeWithWidth(width: 1280.0)!
            }
        }
        else
        {
            if tempImage.size.height > 1280.0
            {
                tempImage = tempImage.resizeWithHeight(height: 1280.0)!
            }
        }

        //
        // compress image then appending it to the upload request
        //

        if  let imageData = UIImageJPEGRepresentation(tempImage, 0.7)
        {
            multipartFormData.append(imageData, withName: "thePhoto", fileName: "image.jpeg", mimeType: "image/jpeg")
        }

        // if u don't have parameters, remove the following loop

        for (key, value) in parameters
        {
            multipartFormData.append(value.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!, withName: key)
        }

    }, usingThreshold:UInt64.init(),
       to: endPoint,
       method: .post,
       headers: headers,
       encodingCompletion: { (result) in

        switch result {

        case .success(let upload, _, _):

            upload.uploadProgress(closure: { (progress) in
                print("Download Progress: \(progress.fractionCompleted)")
            })

            upload.responseJSON { response in
                print("response : \(response)")
                let backendData = response.result.value!
                let status = Parsing_Manager.instance.parsingRequest(backendData)
                completion(status)
            }

            break

        case .failure(let encodingError):
            print("the error is  : \(encodingError.localizedDescription)")
            completion("failed")

            break

        }
    })

} // end of makeMultipartRequest

Удачи!

...