Alamofire and downloading images from server - swift

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:
after I make new call to my API, whole image is downloaded:
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)
}
}

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

Related

Alamofire - How to get API error from AFError

In my quest to implement Alamofire 5 correctly and handle custom error model responses, I have yet to find an accepted answer that has an example.
To be as thorough as possible, here is my apiclient
class APIClient {
static let sessionManager: Session = {
let configuration = URLSessionConfiguration.af.default
configuration.timeoutIntervalForRequest = 30
configuration.waitsForConnectivity = true
return Session(configuration: configuration, eventMonitors: [APILogger()])
}()
#discardableResult
private static func performRequest<T:Decodable>(route:APIRouter, decoder: JSONDecoder = JSONDecoder(), completion:#escaping (Result<T, AFError>)->Void) -> DataRequest {
return sessionManager.request(route)
// .validate(statusCode: 200..<300) // This will kill the server side error response...
.responseDecodable (decoder: decoder){ (response: DataResponse<T, AFError>) in
completion(response.result)
}
}
static func login(username: String, password: String, completion:#escaping (Result<User, AFError>)->Void) {
performRequest(route: APIRouter.login(username: username, password: password), completion: completion)
}
}
I am using it like this
APIClient.login(username: "", password: "") { result in
debugPrint(result)
switch result {
case .success(let user):
debugPrint("__________SUCCESS__________")
case .failure(let error):
debugPrint("__________FAILURE__________")
debugPrint(error.localizedDescription)
}
}
I have noticed that if I use .validate() that the calling function will receive a failure however the response data is missing. Looking around it was noted here and here to cast underlyingError but thats nil.
The server responds with a parsable error model that I need at the calling function level. It would be far more pleasant to deserialize the JSON at the apiclient level and return it back to the calling function as a failure.
{
"errorObject": {
"summary": "",
"details": [{
...
}]
}
}
UPDATE
Thanks to #GIJoeCodes comment I implemented this similar solution using the router.
class APIClient {
static let sessionManager: Session = {
let configuration = URLSessionConfiguration.af.default
configuration.timeoutIntervalForRequest = 30
configuration.waitsForConnectivity = true
return Session(configuration: configuration, eventMonitors: [APILogger()])
}()
#discardableResult
private static func performRequest<T:Decodable>(route:APIRouter, decoder: JSONDecoder = JSONDecoder(), completion:#escaping (_ response: T?, _ error: Error?)->Void) {
sessionManager.request(route)
.validate(statusCode: 200..<300) // This will kill the server side error response...
.validate(contentType: ["application/json"])
.responseJSON { response in
guard let data = response.data else { return }
do {
switch response.result {
case .success:
let object = try decoder.decode(T.self, from: data)
completion(object, nil)
case .failure:
let error = try decoder.decode(ErrorWrapper.self, from: data)
completion(nil, error.error)
}
} catch {
debugPrint(error)
}
}
}
// MARK: - Authentication
static func login(username: String, password: String, completion:#escaping (_ response: User?, _ error: Error?)->Void) {
performRequest(route: APIRouter.login(username: username, password: password), completion: completion)
}
}
Called like this
APIClient.login(username: "", password: "") { (user, error) in
if let error = error {
debugPrint("__________FAILURE__________")
debugPrint(error)
return
}
if let user = user {
debugPrint("__________SUCCESS__________")
debugPrint(user)
}
}
This is how I get the errors and customize my error messages. In the validation, I get the errors outside of the 200..<300 response:
AF.request(
url,
method: .post,
parameters: json,
encoder: JSONParameterEncoder.prettyPrinted,
headers: headers
).validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.responseJSON { response in
switch response.result {
case .success(let result):
let json = JSON(result)
onSuccess()
case .failure(let error):
guard let data = response.data else { return }
do {
let json = try JSON(data: data)
let message = json["message"]
onError(message.rawValue as! String)
} catch {
print(error)
}
onError(error.localizedDescription)
}
debugPrint(response)
}
First, there's no need to use responseJSON if you already have a Decodable model. You're doing unnecessary work by decoding the response data multiple times. Use responseDecodable and provide your Decodable type, in this case your generic T. responseDecodable(of: T).
Second, wrapping your expected Decodable types in an enum is a typical approach to solving this problem. For instance:
enum APIResponse<T: Decodable> {
case success(T)
case failure(APIError)
}
Then implement APIResponse's Decodable to try to parse either the successful type or APIError (there are a lot of examples of this). You can then parse your response using responseDecodable(of: APIResponse<T>.self).

the alamofire isn't doing a proper connection to the api

i am trying to get a response that contain json from openweathermap api,
but from the debugger it seems that when he get to the code block of alamofire its just skips it
here is the block of code that i am using for this task
func printJson(){
Alamofire.request("https://api.openweathermap.org/data/2.5/find?appid=6ad1f143546b8c6d761ecbda6a34a005&q=yavne", method: .get).responseJSON { response in
if response.data != nil {
var json : JSON
do{
json = try JSON(data: response.data!)
print(json)
}catch{}
}
}
}
Use this helper class to make API calls.
class NetworkHandler {
static let shared = NetworkHandler()
func sendRequest(withUrl url:String,andBody body:[String:Any]? = [:],
completionHandler: #escaping ((_ status: Bool,_ response:Any) -> Void)) {
DispatchQueue.global(qos: .userInitiated).async {
Alamofire.request(url, method: .post, parameters: body,encoding: JSONEncoding.default, headers: nil).responseJSON {
response in
guard response.response?.statusCode == 200 else{
completionHandler(false,"Service Temporarily Unavailable.\nPlease check your internet connection or contact your Service provider.")
return
}
switch response.result {
case .success:
completionHandler(true,response.value!)
break
case .failure(let error):
completionHandler(false,error.localizedDescription)
}
}
}
}
}

How to make put request parameters with image Alamofire?

I am sending request through this format to make request with parameters. But how will I sent image as multipart body with this parameters?
class APIManager: NSObject {
enum Router: URLRequestConvertible {
static var baseURLString = baseURLString
static let xSource = X_SOURCE_HEADER
case updateProfile([String: AnyObject])
var method: HTTPMethod {
switch self {
case .updateProfile:
return .put
}
}
var path: String {
switch self {
case .updateStockShelfUnits:
return profile_url
}
}
func asURLRequest() throws -> URLRequest {
let url = try GlobalData.gBaseURLString.asURL()
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
urlRequest.httpMethod = method.rawValue
switch self {
case .updateProfile(let parameters):
urlRequest.setValue(access_token, forHTTPHeaderField: "X-User-Token")
urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters)
}
return urlRequest
}
}
func makeRequestToUpdateProfile(param: [String : AnyObject], img: UIImage, completion: #escaping completionHandlerWithSuccessAndErrorMessage) {
Alamofire.request(Router.updateprofile(param)) .responseJSON { response in
switch response.result {
case .success(let JSON):
print(JSON)
completion(true, "Success")
case .failure(let Error):
print("Request failed with error: \(Error)")
completion(false, Error.localizedDescription)
}
}
}
}
Here what I will do to make a request parameters with image as multipart body? Requesting api with only parameters working well.
Upload Photo / File with parameters and custom headers via Swift 3 and Alamofire 4
// import Alamofire
func uploadWithAlamofire() {
let image = UIImage(named: "bodrum")!
// define parameters
let parameters = [
"hometown": "yalikavak",
"living": "istanbul"
]
Alamofire.upload(multipartFormData: { multipartFormData in
if let imageData = UIImageJPEGRepresentation(image, 1) {
multipartFormData.append(imageData, withName: "file", fileName: "file.png", mimeType: "image/png")
}
for (key, value) in parameters {
multipartFormData.append((value?.data(using: .utf8))!, withName: key)
}}, to: "upload_url", method: .post, headers: ["Authorization": "auth_token"],
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response { [weak self] response in
guard let strongSelf = self else {
return
}
debugPrint(response)
}
case .failure(let encodingError):
print("error:\(encodingError)")
}
})
}
Credit: fatihyildizhan

Uploading Image to API Server using Alamofire

I have a question about Uploading Image to API server using Alamofire.
BaseURL: http://vietnamtravelguide-app.com/quangnam/api_inquangnam/tips/create?user_id=""&token=""
3 parameters : location_id, content, imageName
It's ok to post by POSTMAN
My Code:
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(image, withName: "imageName", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
}, with: path, encodingCompletion: {encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
print(response.result)
switch response.result {
case .success:
let json = JSON(response.result.value!)
if(delegate != nil) {
delegate!.didReceiveResult(json,basePath: basePath)
}
case .failure(let error):
print(error)
} }
case .failure(let encodingError):
print(encodingError)
}
})
with image ( image from parameter casting as Data). When I debug it , i got response.result return failure
You are not uploading the remaining two parameters content and location_id.
Try this one and see the result. I have also used SwiftyJSON here.
This is my APIManager class for all APIs handling.
import Alamofire
import SwiftyJSON
class APIManager: NSObject {
class func apiMultipart(serviceName:String,parameters: [String:Any]?, completionHandler: #escaping (JSON?, NSError?) -> ()) {
Alamofire.upload(multipartFormData: { (multipartFormData:MultipartFormData) in
for (key, value) in parameters! {
if key == "imageName" {
multipartFormData.append(
value as! Data,
withName: key,
fileName: "swift_file.jpg",
mimeType: "image/jpg"
)
} else {
//Data other than image
multipartFormData.append((value as! String).data(using: .utf8)!, withName: key)
}
}
}, usingThreshold: 1, to: serviceName, method: .post, headers: ["yourHeaderKey":"yourHeaderValue"]) { (encodingResult:SessionManager.MultipartFormDataEncodingResult) in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
if response.result.error != nil {
completionHandler(nil,response.result.error as NSError?)
return
}
print(response.result.value!)
if let data = response.result.value {
let json = JSON(data)
completionHandler(json,nil)
}
}
break
case .failure(let encodingError):
print(encodingError)
completionHandler(nil,encodingError as NSError?)
break
}
}
}
}
If you don't have any header then you can leave the field as ["":""] in place of your ["yourHeaderKey":"yourHeaderValue"]
Now in order to call I just formed the parameters in the controller.
var params = [String:AnyObject]()
params["content"] = "something" as AnyObject?
params["location_id"] = "201" as AnyObject?
// Grab your image from some variable or imageView. Here self.profileImage is a UIImage object
if let profileImageData = self.profileImage {
if let imageData = UIImageJPEGRepresentation(profileImageData, 0.5) {
params["imageName"] = imageData as AnyObject?
APIManager.apiMultipart(serviceName: "http://yourAPIURL", parameters: params, completionHandler: { (response:JSON?, error:NSError?) in
//Handle response
})
} else {
print("Image problem")
}
}

How to execute alamofire background upload request?

I need to send zip file to server side.
There is my request which I need to work in background
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 10 // seconds
alamoFireManager = Alamofire.SessionManager(configuration: configuration)
appDeligate.log.debug("request was sended")
alamoFireManager.upload(deligate.data!,
to: deligate.url,
method: .post,
headers: headers)
.uploadProgress(closure: {
progress in
print("Upload Progress: \(progress.fractionCompleted)")
})
.validate()
.responseJSON {}
Now it is work properly, but I need to execute this in background. According to the Alamofire README doc
https://github.com/Alamofire/Alamofire
it says
Creating a Session Manager with Background Configuration
let configuration = URLSessionConfiguration.background(withIdentifier: "com.example.app.background")
let sessionManager = Alamofire.SessionManager(configuration: configuration)
I changed my configuration to correspond background configuration
now it looks like this
let configuration = URLSessionConfiguration.background(withIdentifier: "com.room.myApp")
configuration.timeoutIntervalForRequest = 10 // seconds
alamoFireManager = Alamofire.SessionManager(configuration: configuration)
alamoFireManager.upload(deligate.data!,
to: deligate.url,
method: .post,
headers: headers)
.uploadProgress(closure: {
progress in
print("Upload Progress: \(progress.fractionCompleted)")
})
.validate()
.responseJSON {}
And I get error
*** Terminating app due to uncaught exception 'NSGenericException', reason: 'Upload tasks from NSData are not supported in background sessions.'
*** First throw call stack:
(0x18ec511b8 0x18d68855c 0x18f33808c 0x18f33796c 0x18f336e68 0x100ef9218 0x100f05dc8 0x18f336dc8 0x18f3378cc 0x100255890 0x1002518e8 0x100234200 0x100234448 0x100ef9218 0x100f05dc8 0x100233fc4 0x100255290 0x10029d238 0x10029ae4c 0x10029ac34 0x10006dd78 0x100071044 0x100082708 0x10002b310 0x100ef9258 0x100ef9218 0x100f0726c 0x100f08e2c 0x100f08b78 0x18dce32a0 0x18dce2d8c)
libc++abi.dylib: terminating with uncaught exception of type NSException
What am I doing wrong?
Is it issue from my side or lib side?
Feel free to ask
Edit
there is sending flow
There is how I create zip file
internal func madeRequest() {
DispatchQueue.global().async {
if self.createZipPhotoDir() {
self.appDeligate.log.debug("zip dir was created")
self.serverConnection.makeServerRequest()
} else {
self.appDeligate.log.error("can NOT execute createZipPhotoDir()")
}
}
}
private func createZipPhotoDir() -> Bool {
let withContentsOfDirectory: String! = UtilDirectory.pathToMyCurrentAvatarDir.tweak() // "/var/mobile/Containers/Data/Application/739A895E-7BCA-47A8-911F-70FBC812CEB3/Documents/default#domein.com/AvatarPackage/name/"
let atPath: String! = UtilDirectory.tempZipPath.tweak() // "/var/mobile/Containers/Data/Application/739A895E-7BCA-47A8-911F-70FBC812CEB3/Documents/default#domein.com/tmpZipDir.zip"
return SSZipArchive.createZipFile(atPath: atPath, withContentsOfDirectory: withContentsOfDirectory)
}
zip file is creating ok
Then I make server request
required init() {
configureAlamofireManager()
}
private func configureAlamofireManager() {
let configuration = URLSessionConfiguration.background(withIdentifier: "com.fittingroom.newtimezone.Fitzz")
alamoFireManager = Alamofire.SessionManager(configuration: configuration)
}
internal func makeServerRequest() {
appDeligate.log.debug("request was sended")
alamoFireManager.upload(deligate.data!,
to: deligate.url,
method: .post,
headers: headers)
.uploadProgress(closure: {
progress in
print("Upload Progress: \(progress.fractionCompleted)")
})
.validate()
.responseJSON {
[weak self]
response in
self?.appDeligate.log.debug("response : \(response)")
self?.appDeligate.log.debug(String(describing: response.timeline))
switch response.result {
case .success(let value):
self?.appDeligate.log.debug("succes in server connection response")
let result = self?.getStatusCodeAndData(json: JSON(value))
self?.deligate.onSuccess(statusCode: result?.statusCode, data: result?.data)
case .failure(let error):
self?.appDeligate.log.error("error in UploadingRequest : \(error)")
self?.deligate.onError()
}
}
}
There is a way how I get data to send
internal var data: Data {
var data = Data()
let filePath = UtilDirectory.tempZipPath.tweak()
if let result = UtilFile.exists(path: filePath), result.isFileExist == true, result.whatIsIt == .file {
if let fileData = FileManager.default.contents(atPath: filePath) {
data = fileData
appDeligate.log.debug("*** DATA : \(data) ***")
} else {
print("Could not parse the file")
}
} else {
appDeligate.log.error("some ERROR here: file not exist")
}
return data
}
from Background Transfer Considerations
:
Only upload tasks from a file are supported (uploading from data objects or a stream will fail after the program exits).
that means it is limitation from NSURLSession - you need you upload from a file and then try to solve the other error with file
Update
appDeligate.log.debug("request was sended")
let tempZipFilePath = UtilDirectory.tempZipPath.tweak()
alamoFireManager.upload(tempZipFilePath,
to: deligate.url,
method: .post,
headers: headers)
did you see this section Open Radars:
Open Radars
The following radars have some effect on the current implementation of Alamofire.
rdar://26870455 - Background URL Session Configurations do not work in the simulator
Use below code once, Its working for me
import Alamofire
var sessionManager: Alamofire.SessionManager
var backgroundSessionManager: Alamofire.SessionManager
self.sessionManager = Alamofire.SessionManager(configuration: URLSessionConfiguration.default)
self.backgroundSessionManager = Alamofire.SessionManager(configuration: URLSessionConfiguration.background(withIdentifier: "com.youApp.identifier.backgroundtransfer"))
backgroundSessionManager.upload(multipartFormData: blockFormData!, usingThreshold: UInt64.init(), to: url, method: .post, headers: APIManager.headers(), encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.uploadProgress {
(progress) in
let p = progress.fractionCompleted * 100
uploadProgress(p)
}
upload.responseJSON { response in
switch(response.result) {
case .success(let JSON):
DispatchQueue.main.async {
print(JSON)
}
case .failure(let error):
DispatchQueue.main.async {
print(error)
}
}
}
case .failure(let error):
DispatchQueue.main.async {
print(error)
}
}
})