swiftimagealamofirealamofire-request

Alamofire and downloading images from server


I need to download image as data from the URL and recreate it to UIImage(data:). The problem is, that Alamofire downloads only a small amount of image data on first request: enter image description here

after I make new call to my API, whole image is downloaded:

enter image description here

It really doesn't make any sense to me why it could be like that. The first request always fails to download all the data. This is the code what I'm using to download the data from URL:

func requestWithData(
    _ url: String,
    method: HTTPMethod = .get,
    parameters: Parameters? = nil,
    decoder: JSONDecoder = JSONDecoder(),
    headers: HTTPHeaders? = nil,
    interceptor: RequestInterceptor? = nil
) -> Future<Data, ServerError> {
    return Future({ promise in
        AF.request(
            url,
            method: method,
            parameters: parameters,
            encoding: JSONEncoding.default,
            headers: headers,
            interceptor: interceptor ?? self
        )
        .validate(statusCode: [200, 201, 204, 400, 401])
        .responseData(completionHandler: { (response) in
            switch response.result {
            case .success(let value):
                promise(.success(value))
            case .failure(let error):
                promise(.failure(self.createError(response: response.response, error: error, data: response.data)))
            }
        })
    })
}

func getLocationImage(location: Location) -> Future<Void, ServerError> {
    Future { promise in
        self.networkManager.requestWithData(Endpoint.locationBadge(locationId: location.id, uuid: location.uuid ?? "").url)
            .sink { completion in
                if case .failure(let error) = completion {
                    promise(.failure(error))
                }
            } receiveValue: { [unowned self] imageData in
                self.updateLocationImage(location: location, image: imageData)
                    .sink { completion in
                        if case .failure(let error) = completion {
                            promise(.failure(.init(message: "Error while saving the data", code: .coreData, args: [error.localizedDescription])))
                        }
                    } receiveValue: { _ in
                        promise(.success(()))
                    }
                    .store(in: &subscription)
                
            }
            .store(in: &self.subscription)
    }
}

Solution

  • SOLVED: The problem was with Alamofire request, I was able to resolve the issue with using AlamofireImage framework.