I have a function that download data using Alamofire and then I would like to return that data. Now I know that Alamofire runs asynchronously and in order to to return data I should use completionHandler, however I don't get it how to use it. Since I am not the first with such problem, I found some solutions to similar problems, yet I am not sure to apply them to my case. Here is my code:
func downloadImageFromServer(imageUrl: String) -> (String, String) {
var myData1 = String()
var myData2 = String()
Alamofire.request(.GET, imageUrl)
.responseImage { response in
switch response.result {
case .Success:
if let newImage = response.result.value {
myData1 = //returned image name
myData2 = //edited image name
}
case .Failure:
//Do something
}
}
return (myData1, myData2)
}
Should I do something like this:
func downloadImageFromServer(imageUrl: String, completionHandler: (String?, String?) -> ()) {
var myData1 = String()
var myData2 = String()
Alamofire.request(.GET, imageUrl)
.responseImage { response in
switch response.result {
//if user does have a photo
case .Success:
myData1 = //Something
myData2 = //Something else
completionHandler(myData1 as? String, myData2 as? String)
case .Failure:
//Print error
}
}
}
Update
Yes, my question is very similar to that other question, however in my case, code has to return 2 values and that's where I find difficulties.
Here's my code for gettin values:
func getImages(orders: String, completionHandler: (String?, String?) -> ()) {
justDoIt(orders, completionHandler: completionHandler)
}
and then
getImages(imgURL) { responseObject, error in
print(responseObject)
return
}
And it works, however I am able to access only first value of the two, how to access both?
Your approach is correct. You could use another variable in your closure to see if the request was called properly (or another variable in function, e.g. errorHandler). Example of usage:
downloadImageFromServer(imgURL) { (data1, data2) in
print("Data1: \(data1). Data2: \(data2)")
}
Basic example of adding success/failure variable to your function:
func downloadImageFromServer(imageUrl: String, completionHandler: (Bool, String?, String?) -> ()) {
var myData1 = String()
var myData2 = String()
Alamofire.request(.GET, imageUrl)
.responseImage { response in
switch response.result {
//if user does have a photo
case .Success:
myData1 = //Something
myData2 = //Something else
completionHandler(true, myData1 as? String, myData2 as? String)
case .Failure:
completionHandler(false, nil, nil)
//Print error
}
}
}
Usage of the improved version of downloadImageFromServer():
downloadImageFromServer(imgURL) { (succes, data1, data2) in
if success {
print("Success. Data1: \(data1). Data2: \(data2)")
} else {
print("Error. Data1: \(data1). Data2: \(data2)")
}
}
Related
I have a Login view that asks for a card and password. I consult an API and if the entered data is correct, it sends me a JSON like this. Which return has the button method? How do I send that data to the other view? I occupy Alamofire 5.0 and have my Model class.
#IBAction func myButtonIngresarAction(_ sender: Any) {
guard let carnet = self.txtCarnet.text else {return}
guard let contrasena = self.txtPassword.text else {return}
let ingresologinmodel = IngresoLoginModel(usuario: carnet, password: contrasena)
self.apiCall(IngresoLoginModel: ingresologinmodel){
(result) in
switch result{
case .success(let json):
print(json)
**//This is where I want to send that json with the data to the other view. ******
case .failure(let err):
print(err.localizedDescription)
}
}
}
enum ApiErros: Error {
case custom(message : String)
}
typealias Handler = (Swift.Result<Any?, ApiErros>) -> Void
func apiCall(IngresoLoginModel: IngresoLoginModel, completionHandler: #escaping Handler)
{
let header: HTTPHeaders = [
.contentType("application/json")
]
AF.request("https://url/xxxx/api/Login", method: .post, parameters: IngresoLoginModel,
encoder: JSONParameterEncoder.default, headers: header).response{ response in
debugPrint(response)
switch response.result{
case .success(let data):
do{
let json = try JSONDecoder().decode([LoginModel].self, from: data!)
print(json)
if response.response?.statusCode == 200{
completionHandler(.success(json))
}else{
completionHandler(.failure(.custom(message: "Por favor verifica tu internet")))
}
}
catch
{
print(error)
completionHandler(.failure(.custom(message: "Problemas")))
}
case .failure(let err):
print(err.localizedDescription)
}
}
}
Class model
struct LoginModel: Codable {
let idEmpleado: Int
let Nombre: String
let CodEmpleado: String
let password: String
let idPerfil: Int
let activo: Int
let Descripcion: String
let idRegion: Int
let correo: String
}
This is the json that the Api sends me the data changes them for these example
{
"idEmpleado": 1,
"nombre": “test”,
"codEmpleado": “000000”,
"password": “123”,
"idPerfil": 4,
"activo": 1,
"Descripcion": “test”,
"idregion": 1,
"correo": “test#test.com"
}
many way like create a variable to save this json in OtherViewController and call, self?.otherViewController.json = json
https://learnappmaking.com/pass-data-between-view-controllers-swift-how-to/
use didSet
var page = [Datas]() {
didSet {
self.myVariable = page[0].date!
}
}
typealias Handler = (Swift.Result <[LoginModel]?, ApiErros>) -> Void
#IBAction func myButtonIngresarAction(_ sender: Any) {
guard let carnet = self.txtCarnet.text else {return}
guard let contrasena = self.txtPassword.text else {return}
let ingresologinmodel = IngresoLoginModel(usuario: carnet, password: contrasena)
self.apiCall(IngresoLoginModel: ingresologinmodel){
(result) in
switch result{
case .success(let json):
print(json)
//Here is that I do not know how to send it to the other controller all the json
let viewControllerB = HomeMenuViewController()
viewControllerB.datosPersonales = json!
self.navigationController?.pushViewController(viewControllerB, animated: true)
case .failure(let err):
print(err.localizedDescription)
}
}
}
second controller
class HomeMenuViewController: UIViewController {
#IBOutlet weak var mylabel: UILabel!
var datosPersonales = [LoginModel]()
override func viewDidLoad() {
super.viewDidLoad()
print("***************")
print(datosPersonales)
print("***************")
}
}
I'm having trouble with the ResponseSerializer I get an unresolved identifier and for Response I get an undeclared type. I've read from alamofire migration doc that Response has been changed to multiple types. So I should change Response->DataReponse but this means I can only pass one argument like:
// What I have
Response(<ListWrapper, NSError>)
// What I should change it to?
DataResponse(<ListWrapper>)
How can I still recieve the Error this way and more importantly how do I migrate the extension to alamofire 4?
My class:
class List{
var idNumber: String?
var title: String?
var posterPath: String?
var release: String?
required init(json: JSON, id: Int?)
{
self.idNumber = json[ListFields.Id.rawValue].stringValue
self.title = json[ListFields.Title.rawValue].stringValue
self.posterPath = json[ListFields.PosterPath.rawValue].stringValue
self.release = json[ListFields.Release.rawValue].stringValue
}
class func setURL_APPEND(_ url: String)
{
URL_APPEND = url
}
// MARK: Endpoints
class func endpointForList() -> String
{
return URL_APPEND
}
fileprivate class func getListAtPath(_ path: String, completionHandler: #escaping (ListWrapper?, NSError?) -> Void) {
Alamofire.request(path)
.responseListArray { response in
if let error = response.result.error
{
completionHandler(nil, error)
return
}
completionHandler(response.result.value, nil)
}
}
class func getList(_ completionHandler: #escaping (ListWrapper?, NSError?) -> Void)
{
getListAtPath(List.endpointForList(), completionHandler: completionHandler)
}
}
// Problem is here:
// for ResponseSerializer I get an unresolved identifier
// and for Response I get an undeclared type
extension Alamofire.Request {
func responseListArray(_ completionHandler: #escaping (Response<ListWrapper, NSError>) -> Void) -> Self {
let responseSerializer = ResponseSerializer<ListWrapper, NSError> { request, response, data, error in
guard error == nil else
{
return .failure(error!)
}
guard let responseData = data else {
let failureReason = "Array could not be serialized because input data was nil."
let error = Alamofire.Error.errorWithCode(.dataSerializationFailed, failureReason: failureReason)
return .failure(error)
}
let JSONResponseSerializer = Request.JSONResponseSerializer(options: .allowFragments)
let result = JSONResponseSerializer.serializeResponse(request, response, responseData, error)
switch result {
case .success(let value):
let json = SwiftyJSON3.JSON(value)
let wrapper = ListWrapper()
var allList:Array = Array<List>()
wrapper.totalCount = json["favorite_count"].intValue
// print(json)
let results = json["items"]
// print(results)
for jsonList in results
{
//print(jsonList.1)
let list = List(json: jsonList.1, id: Int(jsonList.0) )
if (list.posterPath == "")
{
continue
}
else
{
//print(movies.posterPath)
allList.append(list)
}
}
wrapper.results = allList
return .success(wrapper)
case .failure(let error):
return .failure(error)
}
}
return response(responseSerializer: responseSerializer,completionHandler: completionHandler)
}
}
Bro try below code see:
func responseListArray(_ completionHandler: #escaping (Response<ListWrapper>) -> Void) -> Self {
let responseSerializer = ResponseSerializer<ListWrapper> { request, response, data, error in
guard error == nil else
{
return .failure(error!)
}
guard let responseData = data else {
return .failure(AFError.responseSerializationFailed(reason: .inputDataNil))
}
let JSONResponseSerializer = Request.JSONResponseSerializer(options: .allowFragments)
let result = JSONResponseSerializer.serializeResponse(request, response, responseData, error)
switch result {
case .success(let value):
let json = SwiftyJSON3.JSON(value)
let wrapper = ListWrapper()
var allList:Array = Array<List>()
wrapper.totalCount = json["favorite_count"].intValue
// print(json)
let results = json["items"]
// print(results)
for jsonList in results
{
//print(jsonList.1)
let list = List(json: jsonList.1, id: Int(jsonList.0) )
if (list.posterPath == "")
{
continue
}
else
{
//print(movies.posterPath)
allList.append(list)
}
}
wrapper.results = allList
return .success(wrapper)
case .failure(let error):
return .failure(error)
}
}
return response(responseSerializer: responseSerializer,completionHandler: completionHandler)
}
I am using Alamofire to make REST calls to my server to get, add, update, and delete objects. What I'm wondering is, is it possible (and recommended) to wrap the Alamofire calls into my own custom objects (DTO), so that I can simply do things like user.delete(id) and user.add(newUser) instead of having Alamofire code all over my codebase? If so, how can I do it so I can return the success and failure handlers (the "promise" from the javascript world)? Something like this:
user.add(newUser)
.success(userObject){
}
.error(response){
}
Here is my current code:
//register a user
let parameters = [“username”: txtUsername.text! , "password": txtPassword.text!]
Alamofire.request(.POST, “http://myserver.com/users", parameters: parameters, encoding: .JSON)
.validate()
.responseObject { (response: Response<User, NSError>) in
if let user = response.result.value {
self.user = user
}
}
}
User.swift
final class User : ResponseObjectSerializable, ResponseCollectionSerializable {
var id: Int
var firstName: String?
var lastName: String?
var email: String?
var password: String?
init?(response: NSHTTPURLResponse, representation: AnyObject) {
id = representation.valueForKeyPath("id") as! Int
firstName = representation.valueForKeyPath("first_name") as? String
lastName = representation.valueForKeyPath("last_name") as? String
email = representation.valueForKeyPath("email") as? String
password = representation.valueForKeyPath("password") as? String
}
static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [User] {
var users: [User] = []
if let representation = representation as? [[String: AnyObject]] {
for userRepresentation in representation {
if let user = User(response: response, representation: userRepresentation) {
users.append(user)
}
}
}
return users
}
//Can I wrap my alamofire calls in methods like this:
func getById(id: Int)
func getAll()
func add(user: User)
func update (user: User)
func delete(id: int)
}
i think a static func is what you want , i wrote a example for it :
final class User{
var valueHandle :((AnyObject) -> ())?
var errorHandle :((NSError)->())?
func success(value:(AnyObject) -> ())->Self{
//pass success handle
self.valueHandle = value
return self
}
func error(error:(NSError)->())->Self{
//pass error handle
self.errorHandle = error
return self
}
static func getById(id: Int)->User{
return userRequest(.GET, urlString: "https://httpbin.org/get", param: ["foo": "bar"])
}
static func userRequest(method:Alamofire.Method , urlString:String ,param:[String: AnyObject]?) -> User {
let user = User()
Alamofire.request(method, urlString, parameters:param)
.validate()
.responseJSON { response in
switch response.result {
case .Success(let value):
//invoke with your back userobj
user.valueHandle?(value)
print(value)
case .Failure(let error):
user.errorHandle?(error)
}
}
return user
}
}
then you can use like :
User.getById(1)
.success { (value) in
print("value = \(value)")
}
.error { (error) in
print("error = \(error)")
}
hope it be helpful :D
I am new to Swift, and am not able to figure out how to deserialize a JSON array to an array of Swift objects. I'm able to deserialize a single JSON user to a Swift user object fine, but just not sure how to do it with a JSON array of users.
Here is my User.swift class:
class User {
var id: Int
var firstName: String?
var lastName: String?
var email: String
var password: String?
init (){
id = 0
email = ""
}
init(user: NSDictionary) {
id = (user["id"] as? Int)!
email = (user["email"] as? String)!
if let firstName = user["first_name"] {
self.firstName = firstName as? String
}
if let lastName = user["last_name"] {
self.lastName = lastName as? String
}
if let password = user["password"] {
self.password = password as? String
}
}
}
Here's the class where I'm trying to deserialize the JSON:
//single user works.
Alamofire.request(.GET, muURL/user)
.responseJSON { response in
if let user = response.result.value {
var swiftUser = User(user: user as! NSDictionary)
}
}
//array of users -- not sure how to do it. Do I need to loop?
Alamofire.request(.GET, muURL/users)
.responseJSON { response in
if let users = response.result.value {
var swiftUsers = //how to get [swiftUsers]?
}
}
The best approach is the use Generic Response Object Serialization provided by Alamofire here is an example :
1) Add the extension in your API Manager or on a separate file
public protocol ResponseObjectSerializable {
init?(response: NSHTTPURLResponse, representation: AnyObject)
}
extension Request {
public func responseObject<T: ResponseObjectSerializable>(completionHandler: Response<T, NSError> -> Void) -> Self {
let responseSerializer = ResponseSerializer<T, NSError> { request, response, data, error in
guard error == nil else { return .Failure(error!) }
let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let result = JSONResponseSerializer.serializeResponse(request, response, data, error)
switch result {
case .Success(let value):
if let
response = response,
responseObject = T(response: response, representation: value)
{
return .Success(responseObject)
} else {
let failureReason = "JSON could not be serialized into response object: \(value)"
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
case .Failure(let error):
return .Failure(error)
}
}
return response(responseSerializer: responseSerializer, completionHandler: completionHandler)
}
}
public protocol ResponseCollectionSerializable {
static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self]
}
extension Alamofire.Request {
public func responseCollection<T: ResponseCollectionSerializable>(completionHandler: Response<[T], NSError> -> Void) -> Self {
let responseSerializer = ResponseSerializer<[T], NSError> { request, response, data, error in
guard error == nil else { return .Failure(error!) }
let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let result = JSONSerializer.serializeResponse(request, response, data, error)
switch result {
case .Success(let value):
if let response = response {
return .Success(T.collection(response: response, representation: value))
} else {
let failureReason = "Response collection could not be serialized due to nil response"
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
case .Failure(let error):
return .Failure(error)
}
}
return response(responseSerializer: responseSerializer, completionHandler: completionHandler)
}
}
2) update your model object like this:
final class User: ResponseObjectSerializable, ResponseCollectionSerializable {
let username: String
let name: String
init?(response: NSHTTPURLResponse, representation: AnyObject) {
self.username = response.URL!.lastPathComponent!
self.name = representation.valueForKeyPath("name") as! String
}
static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [User] {
var users: [User] = []
if let representation = representation as? [[String: AnyObject]] {
for userRepresentation in representation {
if let user = User(response: response, representation: userRepresentation) {
users.append(user)
}
}
}
return users
}
}
3) then you can use it like that :
Alamofire.request(.GET, "http://example.com/users")
.responseCollection { (response: Response<[User], NSError>) in
debugPrint(response)
}
Source: Generic Response Object Serialization
Useful Link: Alamofire JSON Serialization of Objects and Collections
Since you are using Alamofire to make your requests why don't you give a chance to Hearst-DD ObjectMapper it has an Alamofire extension AlamofireObjectMapper. I think it'll save you time!
I would loop through them then add each user to an array (preferably a property of the VC and not an instance variable) but here is an example.
Alamofire.request(.GET, "YourURL/users")
.responseJSON { response in
if let users = response.result.value {
for user in users {
var swiftUser = User(user: user as! NSDictionary)
//should ideally be a property of the VC
var userArray : [User]
userArray.append(swiftUser)
}
}
}
You could also try EVReflection https://github.com/evermeer/EVReflection
It's even more simple, i.e. to parse JSON (code snippet taken from EVReflection link):
let json:String = "{
\"id\": 24,
\"name\": \"Bob Jefferson\",
\"friends\": [{
\"id\": 29,
\"name\":
\"Jen Jackson\"}]}"
you can use this class:
class User: EVObject {
var id: Int = 0
var name: String = ""
var friends: [User]? = []
}
in this way:
let user = User(json: json)
I am having a little trouble with my swift code. The ending return statement runs before the the JSON value is stored so it keeps giving me nil. How can i do the return after the value been received?
func getArticleInfo(Id: String) -> String {
let url = val1 + val2 + val3
Alamofire.request(.GET, url).responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
let json = JSON(value)
let singleAsset = json["url"].string
}
}
case .Failure(let error):
print(error)
}
}
return singleAsset
}
Thanks for the help the other problem I’m having. SEE BELOW
I am trying to get the categories to populate with all the information then call the vc.displayCatName() after its done. But it does it late and i have to refresh the page before i can see the information.
Above that is just me assigning the JSON values to the keys that populate categories BELOW. But the vc.displayCatName() is a function from another view controller but it gets run before the category values are populated. So the only way i see the values is if i refresh the page manually using the Pull to Refresh. So i want the information to be populated then vc.displayCatName() should run
self.getAsset(id!) { (result) -> Void in
print("this is result \(result)")
let categories = Categories (categoryName: catName, imageId: id, catIdNumber: catIdNumber, imageUrl: result)
vc.cats.append(categories)
}
}
}
dispatch_async(dispatch_get_main_queue()) {
vc.displayCatName()
}
}
The reason for this is because the call that you are making is asynchronous in nature. Instead consider using a completion handler.
func getArticleInfo(Id: String, success: (String) -> Void ) {
let url = "www.Test.com"
Alamofire.request(.GET, url).responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
let json = JSON(value)
let singleAsset = json["url"].string
success(singleAsset!)
}
case .Failure(let error):
print(error)
success("TEST")
}
}
}
To Call:
getArticleInfo("test") { (asset) -> Void in
print(asset)
}