Created observable doesn't emit anything - swift

I'm trying to create a function which returns Observable<(HTTPURLResponse, Any)> using RxAlamofire:
class APIManager {
let disposeBag = DisposeBag()
func getResponse(credentialData: Credentials, ulr: String)->Observable<(HTTPURLResponse, Any)>{
let credentialData = "\(credentialData.username):\(credentialData.password)".data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!
let base64Credentials = credentialData.base64EncodedString()
let headers = ("Authorization", "Basic \(base64Credentials)")
let header = HTTPHeaders.init(dictionaryLiteral: headers)
return Observable.create{ observer in
requestJSON(.get, ulr, parameters: nil, encoding: JSONEncoding.default, headers: header)
.subscribe(onNext: { response in
observer.onNext(response)
} ,
onError: { error in
observer.onError(error)
},
onCompleted: {},
onDisposed: {}).disposed(by: self.disposeBag)
return Disposables.create()
}
}
}
The code into onNext is not executed; it's going through onDisposed only.
How can I fix it?

Why are you wrapping requestJSON function with another Observable which is just forwarding the same element and error, when that function is already returning the Observable you need?.
Isn't this enough for you?
class APIManager {
func getResponse(credentialData: Credentials, ulr: String) -> Observable<(HTTPURLResponse, Any)> {
let credentialData = "\(credentialData.username):\(credentialData.password)"
.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!
let base64Credentials = credentialData.base64EncodedString()
let headers = ("Authorization", "Basic \(base64Credentials)")
let header = HTTPHeaders.init(dictionaryLiteral: headers)
return requestJSON(.get, ulr, parameters: nil, encoding: JSONEncoding.default, headers: header)
}
}

Related

Swift Alamofire Async Issue

new to swift here.
I'm trying to make an AF.request call inside another AF.request call and everything works fine.
The issue is that the fetchAllUsers() gets called after everything loads up. So instead of getting all the users right away, I have to refresh the page in order to get the fetchAllUsers() to execute.
I thought using closures would avoid this problem but it's still occurring.
Am I doing something wrong?
func fetchAllUsers(completionHandler: #escaping ([User]) -> Void) {
let allUsersUrl = baseUrl + "users/"
let headers: HTTPHeaders = [
.authorization(bearerToken: NetworkManager.authToken)
]
if let url = URL(string: allUsersUrl) {
AF.request(url, headers: headers).responseDecodable(of: [User].self) { response in
if let users = response.value {
completionHandler(users)
} else {
print("Users is empty")
}
}
} else {
print("URL error")
}
}
func login(param: [String:String], completionHandler: #escaping (Int) -> Void) {
let loginUrl = baseUrl + "auth/login"
// Sets the Logged In User
AF.request(loginUrl, method: .post, parameters: param, encoding: JSONEncoding.default, headers: nil).responseString { response in
if let data = response.data {
let authTokenString = String(decoding: data, as:UTF8.self).components(separatedBy: " ")
// Sets the authentication token
NetworkManager.authToken = authTokenString[1]
self.fetchAllUsers { users in
for user in users {
if param["username"] == user.username {
HomeViewModel.loggedInUser = user
}
}
}
completionHandler(response.response!.statusCode)
}
}
}
Pass completion handler of main function and status code to fetchAllUsers and call it there after it's own completion handler
completionHandler(response.response!.statusCode) was being executed before self.fetchAllUsers closure because it was waiting for api response to complete. completionHandler(response.response!.statusCode) was destroying self.fetchAllUsers closure before it is executed, so I called completionHandler(response.response!.statusCode) inside self.fetchAllUsers after it's closure
completionHandler(users)
mainCompletion(statusCode)
Complete code works following
func fetchAllUsers(statusCode:Int, mainCompletion: #escaping (Int) -> Void, completionHandler: #escaping ([User]) -> Void) {
let allUsersUrl = baseUrl + "users/"
let headers: HTTPHeaders = [
.authorization(bearerToken: NetworkManager.authToken)
]
if let url = URL(string: allUsersUrl) {
AF.request(url, headers: headers).responseDecodable(of: [User].self) { response in
if let users = response.value {
completionHandler(users)
mainCompletion(statusCode)
} else {
print("Users is empty")
}
}
} else {
print("URL error")
}
}
func login(param: [String:String], completionHandler: #escaping (Int) -> Void) {
let loginUrl = baseUrl + "auth/login"
// Sets the Logged In User
AF.request(loginUrl, method: .post, parameters: param, encoding: JSONEncoding.default, headers: nil).responseString { response in
if let data = response.data {
let authTokenString = String(decoding: data, as:UTF8.self).components(separatedBy: " ")
// Sets the authentication token
NetworkManager.authToken = authTokenString[1]
self.fetchAllUsers(statusCode: response.response!.statusCode, mainCompletion: completionHandler) { users in
for user in users {
if param["username"] == user.username {
HomeViewModel.loggedInUser = user
}
}
}
}
}
}

Result of call to 'subscribe(onNext:onError:onCompleted:onDisposed:)' is unused

I am trying to create function which return Observable<(HTTPURLResponse, Any)> using RxAlamofire:
func getResponse(credentialData: Credentials, ulr: String)->Observable<(HTTPURLResponse, Any)>{
let credentialData = "\(credentialData.username):\(credentialData.password)".data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!
let base64Credentials = credentialData.base64EncodedString()
let headers = ("Authorization", "Basic \(base64Credentials)")
let header = HTTPHeaders.init(dictionaryLiteral: headers)
return Observable.create{ observer in
requestJSON(.get, ulr, parameters: nil, encoding: JSONEncoding.default, headers: header)
.subscribe(onNext: { response in
observer.onNext(response)
} ,
onError: { error in
observer.onError(error)
})
return Disposables.create()
}
}
}
but I get this below warning:-
Result of call to 'subscribe(onNext:onError:onCompleted:onDisposed:)'
is unused
How to fix it? After adding .disposed(by: disposeBag) my function isn't working.
Hello you have to add your request into a DisposeBag :
return Observable.create { observer in
requestJSON(.get, ulr, parameters: nil, encoding: JSONEncoding.default, headers: header)
.subscribe(onNext: { response in
observer.onNext(response)
}, onError: { error in
observer.onError(error)
}).disposed(by: disposeBag)
return Disposables.create()
}
That should works.

How can I write a generic wrapper for alamofire request in swift?

How can I write a generic wrapper for alamofire request ?
How can I convert the POST and GET function to Generic function in the following code?
I need to have generic request functions that show different behaviors depending on the type of data received.
Also, Can the response be generic?
My non-generic code is fully outlined below
import Foundation
import Alamofire
import SwiftyJSON
// for passing string body
extension String: ParameterEncoding {
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var request = try urlRequest.asURLRequest()
request.httpBody = data(using: .utf8, allowLossyConversion: false)
return request
}
}
public class ConnectionManager {
func Post (FirstName: String, LastName: String, NationalID: String, NationalCode: String, BirthDate: Date,Image: String,isFemale: Bool,Age:Int64,Avg:Double, completion: #escaping CompletionHandler) {
let body: [String:Any] = [
"FirstName":FirstName,
"LastName": LastName,
"NationalID": NationalID,
"NationalCode": NationalCode,
"BirthDate":BirthDate,
"Image": Image,
"isFemale": isFemale,
"Age": Age,
"Avg": Avg
]
Alamofire.request(BASE_URL, method: .post, parameters: body, encoding: JSONEncoding.default, headers: HEADER).responseJSON { (response) in
if response.response?.statusCode == 200 {
guard let data = response.result.value else { return }
print(data)
completion(true)
} else {
print("error reg auth service")
guard let er = response.result.value else { return }
print(er)
completion(false)
debugPrint(response.result.error as Any)
}
}
}
func get(FirstName: String, LastName: String, NationalID: String, NationalCode: String, BirthDate: Date,Image: String,isFemale: Bool,Age:Int64,Avg:Double, completion: #escaping CompletionHandler) -> [Person] {
let body: [String:Any] = [
"FirstName":FirstName,
"LastName": LastName,
"NationalID": NationalID,
"NationalCode": NationalCode,
"BirthDate":BirthDate,
"Image": Image,
"isFemale": isFemale,
"Age": Age,
"Avg": Avg
]
Alamofire.request(BASE_URL, method: .get, parameters: body, encoding: JSONEncoding.default, headers: HEADER).responseJSON { (response) in
if response.response?.statusCode == 200 {
print("no error login in authservice")
guard let data = response.result.value else { return }
print(data)
completion(true)
}
else if response.response?.statusCode == 400 {
print("error 400 login in authservice")
guard let er = response.result.value else { return }
print(er)
debugPrint(response.result.error as Any)
completion(false)
} else {
print("error ## login in authservice")
guard let er = response.result.value else { return }
print(er)
debugPrint(response.result.error as Any)
completion(false)
}
}
return [Person]()
}
}
The best idea is to use the URLRequestConvertible Alamofires protocol and create your own protocol and simple structs for every API request:
import Foundation
import Alamofire
protocol APIRouteable: URLRequestConvertible {
var baseURL: String { get }
var path: String { get }
var method: HTTPMethod { get }
var parameters: Parameters? { get }
var encoding: ParameterEncoding { get }
}
extension APIRouteable {
var baseURL: String { return URLs.baseURL }
// MARK: - URLRequestConvertible
func asURLRequest() throws -> URLRequest {
let url = try baseURL.asURL().appendingPathComponent(path)
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = method.rawValue
return try encoding.encode(urlRequest, with: parameters)
}
}
and request can look like this:
struct GetBooks: APIRouteable {
var path: String
var method: HTTPMethod
var parameters: Parameters?
var encoding: ParameterEncoding
}
and inside the APIClient prepare the generic method:
func perform<T: Decodable>(_ apiRoute: APIRouteable,
completion: #escaping (Result<T>) -> Void) {
let dataRequest = session
.request(apiRoute)
dataRequest
.validate(statusCode: 200..<300)
.responseDecodable(completionHandler: { [weak dataRequest] (response: DataResponse<T>) in
dataRequest.map { debugPrint($0) }
let responseData = response.data ?? Data()
let string = String(data: responseData, encoding: .utf8)
print("Repsonse string: \(string ?? "")")
switch response.result {
case .success(let response):
completion(.success(response))
case .failure(let error):
completion(.failure(error))
}
})
}
and use it:
func getBooks(completion: #escaping (Result<[Book]>) -> Void) {
let getBooksRoute = APIRoute.GetBooks()
perform(getBooksRoute, completion: completion)
}

unable to load JSON data in 'data' array

when I call this function the array 'data' is showing empty square brackets, it is not giving me any errors though
here is the code :-
import Foundation
import Alamofire
import SwiftyJSON
class Networking {
var data = [Item]()
let tVC = TableViewController()
let url = "https://api.coinmarketcap.com/v1/ticker/"
func getCoinData(url: String) {
Alamofire.request(url, method: .get)
.responseJSON { response in
if response.result.isSuccess {
let coinJSON : JSON = JSON(response.result.value!)
for i in 0..<coinJSON.count{
let coinName = Item(bitJSON: coinJSON[i])
self.data.append(coinName)
self.tVC.tableView.reloadData()
}
}
else {
print("Error: \(String(describing: response.result.error))")
}
}
}
}
Try this one.
Change your url, method is "Get" and your mapping model.
public static func getArrayInformation(completionHandler: #escaping (APIResponse) -> Void) {
let url = "your url"
let params: Parameters = ["username": "admin",
"password": "1234"]
Alamofire.request(url,
method: .post,
parameters: params,
encoding: JSONEncoding.default,
headers: ["Content-Type": "application/json"])
.responseDecodableObject(keyPath: nil, decoder: JSONDecoder(), completionHandler: { (handler: DataResponse<[Your Object Array]>) in
completionHandler(handler.result.value ?? [Your Object Array]())
})
}
why you reload Table every loop iteration , and instead Loop use Map
class Networking {
var data = [Item]()
let tVC = TableViewController()
let url = "https://api.coinmarketcap.com/v1/ticker/"
func getCoinData(url: String) {
Alamofire.request(url, method: .get)
.responseJSON { response in
if response.result.isSuccess {
let coinJSON : JSON = JSON(response.result.value!)
data = coinJSON.map({ (coinJson) -> Item in
return Item(bitJSON: coinJson)
})
DispatchQueue.main.async {
self.tVC.tableView.reloadData()
}
}
else {
print("Error: \(String(describing: response.result.error))")
}
}
}
}

Alamofire Post Request is not Executed

I'm making a POST Request to my API. All of a sudden the request is being skipped. I have tried to debug into it, but until now without success.
This is my request:
#IBAction func checkLogin(_ sender: Any) {
guard let managedContext = self.managedObjectContext else { return }
let user = NSEntityDescription.insertNewObject(forEntityName: User.identifier, into: managedContext) as! User
let url = ""
let parameters: Parameters =
["username" : usernameTextField.text!, "password" : passwordTextField.text!]
Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.default).responseJSON { (responseData) -> Void in
let results = JSON(responseData.result.value!)
print(results)
user.firstName = results["firstname"].string!
let responseString : String = responseData.response?.allHeaderFields["Set-Cookie"] as! String
if let range = responseString.range(of: ";"){
let startIndex = (responseString.range(of: "="))
let cookie = responseString[(startIndex?.upperBound)!...range.lowerBound]
user.setValue(cookie, forKey: "token")
}
} do {
try self.dataController.saveContext()
}catch {
print("Save Error User")
}
I'm Using Alamofire 4.5 with Swift 3.1.
Please use different types of data request handling block and check again.
Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.default)
.responseJSON { response in
print("JSON Response")
}
.responseData { response in
print("Data Response")
}
.responseString { response in
print("String Response")
}
.responsePropertyList { response in
print("PropertyList Response")
}