0

I am trying to upload an image to PHP server using alamofire. the image is successfully uploaded to the server actually, but when I fetch the data back using the same link/image path, I always get the old image back, not the new one I just upload. the old image actually no longer available on the server, but it seems cached / persist in the app.

here is the code I use to upload an image using alamofire and to download the image back

   struct NetworkingService {

static func fetchData(url: URL, completion: @escaping (APIResult<Data>) -> Void) {
        // this function will be used to download image data from the server

        Alamofire.SessionManager.default
            .requestWithoutCache("http://localhost/Twitter/Avatar/53/avatar.jpeg").response { response in
                print("Request: \(response.request!)")
                print("Response: \(response.response!)")
                print("Error: \(response.error!)") <--- i got a fatal error in here
        }

        let request = URLRequest(url:url)
        Alamofire.request(request).responseData { (response) in

            if response.error != nil {
                print(response.error!)
                completion(.failure(response.error!))
            }

            guard let data = response.data else {return}

            completion(.success(data)) <-- the Data will be used to generate UIImage later
        }

    }


    static func uploadAvatar (image: UIImage, endPoint: EndPoint, completion : @escaping (APIResult<Any>) -> Void ) {


        let urlString = "\(endPoint.baseURL)\(endPoint.path)"

        let imgData = UIImageJPEGRepresentation(image, 0.5)!

        let url = try! URLRequest(url: URL(string: urlString)!, method: .post, headers: nil)


        Alamofire.upload(
            multipartFormData: { multipartFormData in
                multipartFormData.append(imgData, withName: "file", fileName: "avatar.jpeg", mimeType: "image/jpeg")

                for (key, value) in endPoint.parameters {
                    multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
                }
        },
            with: url,
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        if((response.result.value) != nil) {
                            guard let json = response.result.value as? [String:Any] else {return}

                            guard let id = json["id"] as? String,
                                let username = json["username"] as? String,
                                let fullname = json["fullname"] as? String,
                                let email = json["email"] as? String,
                                let avatar = json["avatar"] as? String else {
                                    return
                            }


                            let userData : [String : Any] = [
                                "userID" : id,
                                "username" : username,
                                "email" : email,
                                "avatar" : avatar,
                                "fullname" : fullname
                            ]
                            completion(.success(userData))


                        } else {

                        }
                    }
                case .failure(let encodingError):
                    completion(.failure(encodingError))
                    print(encodingError)
                    break
                }
        }
        )


}


extension Alamofire.SessionManager {
    @discardableResult
    open func requestWithoutCache(
        _ url: URLConvertible,
        method: HTTPMethod = .get,
        parameters: Parameters? = nil,
        encoding: ParameterEncoding = URLEncoding.default,
        headers: HTTPHeaders? = nil)// also you can add URLRequest.CachePolicy here as parameter
        -> DataRequest
    {
        do {
            var urlRequest = try URLRequest(url: url, method: method, headers: headers)
            urlRequest.cachePolicy = .reloadIgnoringCacheData // <<== Cache disabled
            let encodedURLRequest = try encoding.encode(urlRequest, with: parameters)
            return request(encodedURLRequest)
        } catch {
            // TODO: find a better way to handle error
            print(error)
            return request(URLRequest(url: URL(string: "http://example.com/wrong_request")!))
        }
    }
}

I found a similar case with my problem in here why i get different image when downloading to the same path?

it is said that i have to remove all the caching policies, by using this code

let session = URLSession(configuration: .ephemeral)

if that is the problem, so how do i achieve this using alamofire ? since the solution above is using native URL session function

i have tried to implement the solution in this one but it doesnt work How to disable caching in Alamofire

Thanks in advance :)

Alexa289
  • 8,089
  • 10
  • 74
  • 178
  • 1
    Please see this answer https://stackoverflow.com/a/42529641/7842542 – Malik Jan 31 '18 at 08:33
  • You get the cached image from Alamofire. You can force download the image. –  Jan 31 '18 at 10:04
  • @Balanced could you please explain more about 'force download image'? I have tried the solution in caching alamofire in here https://stackoverflow.com/questions/32199494/how-to-disable-caching-in-alamofire but it doesnt work for me – Alexa289 Jan 31 '18 at 10:13
  • Can you edit your question with the code you tried, the extension in the answer should work. –  Jan 31 '18 at 10:20
  • i have edited the question, i don't know why i got fatal error when execute print("Error: \(response.error!)") <--- i got a fatal error in here. thank you very much – Alexa289 Jan 31 '18 at 10:31
  • i have finally found the solution by using this line of code when downloading the data URLCache.shared.removeCachedResponse(for: request) . Thanks :) – Alexa289 Jan 31 '18 at 10:49

0 Answers0