9

we are working to get an upload to an API with a POST method. We are trying to push an image. We are getting the next error

success(request: 2018-02-03 16:27:53.087629-0800 Optimio-iOS[5425:201118] CredStore - performQuery - Error copying matching creds.  Error=-25300, query={
    class = inet;
    "m_Limit" = "m_LimitAll";
    ptcl = htps;
    "r_Attributes" = 1;
    sdmn = "llegoelbigotes.ubiqme.es";
    srvr = "llegoelbigotes.ubiqme.es";
    sync = syna;
}
$ curl -v \
-X POST \
-H "Content-Type: multipart/form-data; boundary=alamofire.boundary.7105b62be90b880b" \
-H "Accept-Language: en;q=1.0, es-ES;q=0.9" \
-H "Authorization: Token 1b0ad885a95334154ca3bfa79b3f52ca35c25e0e" \
-H "User-Agent: Optimio-iOS/1.0 (Ubiqme-com.ubiqme.ubiqme; build:1; iOS 11.2.0) Alamofire/4.6.0" \
-H "Accept-Encoding: gzip;q=1.0, compress;q=0.5" \
"https://llegoelbigotes.ubiqme.es/api/new-ticket", streamingFromDisk: true, streamFileURL: Optional(file:///Users/polvallsortiz/Library/Developer/CoreSimulator/Devices/EE663E81-6611-4B69-ABD6-AF97D19D6FB7/data/Containers/Data/Application/E7B9F357-DD51-4512-8173-37C932C0E4B9/tmp/org.alamofire.manager/multipart.form.data/74C9B75E-614D-4FCD-9DBC-1F5D07D773C4))

Our code is the next one:

 func myImageUploadRequest() {
    guard let urlStr = "https://llegoelbigotes.ubiqme.es/api/new-ticket".addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed),
    let url = URL(string: urlStr)
    else {return}
    let isPaymentCard = card ? "true" : "false"
    let headers: HTTPHeaders = ["Authorization": "Token \(token!)"]
    let param = [ "comment": comment, "category": String(category), "amount": String(money), "payment_card": isPaymentCard ]
    Alamofire.upload(multipartFormData: { multipartFormData in
        if let imageData = UIImageJPEGRepresentation(self.image,0.5)
        { multipartFormData.append(imageData,withName:"image",fileName:"image.jpeg",mimeType:"image/jpeg") }
        for(key,value) in param {
            multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
        }
    }, usingThreshold: UInt64.init(),
       to: urlStr,
       method: .post,
       headers: headers) {(result) in
        print(result)
        switch result{
        case .success(let upload, _, _):
            upload.responseJSON {
                response in
                print("Succesfully uploaded")
                if let err = response.error{
                    print(err)
                    return
                }
            }
        case .failure(let error):
            print("Error in upload: \(error.localizedDescription)")
            print(error)

        }

    }

}

Anyone can show us some tips or say what might be wrong? Thanks to all the community!

Pol Valls Ortiz
  • 282
  • 2
  • 14

1 Answers1

0

-> I have created a dynamic function for uploading Image and Files you can even upload multiple images and files my this

func makeFormDataAPICall<T: Codable>(url: String, params: [String: Any], objectType: T.Type,
                                                 success: @escaping(_ responseObject: T) -> Void,
                                                 failure: @escaping (_ error: String) -> Void) {
        let name = self.randomNumberWith(digits: 6)
        self.headers = [kAuthorization: self.userData?.authToken ?? ""]
        //Network check
        if Utilities.isConnectedToNetwork() {
            guard let urlIs = URL(string: url) else {
                failure(ServerAPI.errorMessages.kServerDownError)
                return
            }
            // Almofire upload request
            AF.upload(multipartFormData: { multiPartData in
                for (key, value) in params {
                    if value is UIImage {
                        let img = (value as? UIImage)?.jpegData(compressionQuality: 0.5)
                        multiPartData.append(img!, withName: key, fileName: "img_\(name).jpeg", mimeType: "image/jpeg")
                    } else if value is NSArray {
                        for childValue in value as? NSArray ?? [] {
                            if childValue is UIImage {
                                let img = (childValue as? UIImage)?.jpegData(compressionQuality: 0.5)
                                multiPartData.append(img!, withName: key, fileName: "profile_image.png", mimeType: "image/jpeg")
                            }
                        }
                    } else if value is NSURL || value is URL {
                        do {
                            guard let pdf: URL = value as? URL else { return }
                            let name = pdf.lastPathComponent
                            let mimeType = pdf.mimeType()
                            let pdfData = try Data(contentsOf: pdf)
                            multiPartData.append(pdfData, withName: key, fileName: name, mimeType: mimeType)
                        } catch { print(error) }
                    } else {
                        if value is String || value is Int || value is Bool {
                            multiPartData.append("\(value)".data(using: .utf8)!, withName: key)
                        }
                    }
                }
            }, to: urlIs,method: .post, headers: headers).responseDecodable(of: FetchAPI<T>.self) { response in
                // preetify data
                if let data = response.data {
                    let str = data.prettyPrintedJSONString!
                    Logger.logResponse(ofAPI: "\(urlIs)", logType: .success, object: str)
                }
                // response result
                switch response.result {
                case .success(let data):
                    // check auth token Exp condition
                    if data.statusCode == 401 {
                        let appDelegate = AppDelegate.shared()
                        let rootVC = R.storyboard.auth.authNavigationController()!
                        appDelegate.window?.rootViewController = rootVC
                        return
                    }
                    // check flag status
                    if data.flag! { success(data.data!) } else { failure(data.message!) }
                case .failure(let error):
                    failure("Something went wrong.")
                    Logger.log(logType: .error, object: error.localizedDescription)
                }
            }
        } else { failure(ServerAPI.errorMessages.kNoInternetConnectionMessage) }
    }

-> Usage

APIManager.shared.makeFormDataAPICall(url: ServerAPI.editProfile, params: params, objectType: User.self, success: { response in
            success(response)
            print(response)
        }, failure: { error in
            failure(error)
        }) // 1st Parameter is URL 2nd Parameter are params to send 
//3rd parameter is Object to which you want to convert the Json data into 
//4th and 5th parameter are compilation handler which gives you response and errors accordingly

-> you can remove auth token conditions which I have written for myself

-> if you are passing data in json you just have to write JSONEncoding: JSONEncoding.default before "header parameter" in almofire function