AWS get response as data, not JSON (for using with Codable) - swift

Not familiar enough with AWS, but I have some Codable models I need to initialize from AWS. I'm getting JSON result from AWSTask.result (which is AnyObject). I'm trying to avoid creating Data from Dictionaty and back to a struct (to be able to use Codable).
I tied to use AWSNetworkingHTTPResponseInterceptor, but it was never got called and I couldn't find any example of using it.
self.getGatewayClient { (apiGatewayClient: AWSAPIGatewayClient?) in
let queryParameters = ...
let headerParameters = ...
apiGatewayClient?.invokeHTTPRequest(
"GET",
urlString: "/path",
pathParameters: [:],
queryParameters: queryParameters,
headerParameters: headerParameters,
body: nil,
responseClass: nil
).continueWith { (task: AWSTask<AnyObject>) -> Any? in
if let data = task... { // Get response as Data type??
}
if let result = task.result as? [String: Any] {
// Thanks, but I have a Codable, so I'll just take the data thank you.
}
return task
}
}

AWS's AWSAPIGatewayClient has two functions, one is: invokeHTTPRequest (which was what was used). There is another one called invoke, which returns data. It takes a AWSAPIGatewayRequest request:
func someTask(completion: #escaping (String?) -> ()) {
self.getGatewayClient { (apiGatewayClient: AWSAPIGatewayClient?) in
let request = AWSAPIGatewayRequest(httpMethod: "GET",
urlString: "/path",
queryParameters: queryParameters,
headerParameters: headerParameters,
httpBody: nil)
apiGatewayClient?.invoke(request).continueOnSuccessWith { response in
if let data = response.result?.responseData {
// Init Codable using data
}
}
}
}

Related

Accessing Google API data from within 3 async callbacks and a function in SwiftUI

I know this question is asked a lot, but I can't figure out how to apply any answers to my program. Sorry in advance this async stuff makes absolutely zero sense to me.
Basically, I have a button in SwiftUI that, when pressed, calls a function that makes two API calls to Google Sheets using Alamofire and GoogleSignIn.
Button("Search") {
if fullName != "" {
print(SheetsAPI.nameSearch(name: fullName, user: vm.getUser()) ?? "Error")
}
}
This function should return the values of some cells on success or nil on an error. However, it only ever prints out "Error". Here is the function code.
static func nameSearch<S: StringProtocol>(name: S, advisory: S = "", user: GIDGoogleUser?) -> [String]? {
let name = String(name)
let advisory = String(advisory)
let writeRange = "'App Control'!A2:C2"
let readRange = "'App Control'!A4:V4"
// This function can only ever run when user is logged in, ! should be fine?
let user = user!
let parameters: [String: Any] = [
"range": writeRange,
"values": [
[
name,
nil,
advisory
]
]
]
// What I want to be returned
var data: [String]?
// Google Identity said use this wrapper so that the OAuth tokens refresh
user.authentication.do { authentication, error in
guard error == nil else { return }
guard let authentication = authentication else { return }
// Get the access token to attach it to a REST or gRPC request.
let token = authentication.accessToken
let headers: HTTPHeaders = ["Authorization": "Bearer \(token)"]
AF.request("url", method: .put, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseString { response in
switch response.result {
case .success:
// I assume there is a better way to make two API calls...
AF.request("anotherURL", headers: headers).responseDecodable(of: NameResponseModel.self) { response2 in
switch response2.result {
case .success:
guard let responseData = response2.value else { return }
data = responseData.values[0]
// print(responseData.values[0]) works fine
case .failure:
print(response2.error ?? "Unknown error.")
data = nil
}
}
case .failure:
print(response.error ?? "Unknown error.")
data = nil
}
}
}
// Always returns nil, "Unknown error." never printed
return data
}
The model struct for my second AF request:
struct NameResponseModel: Decodable { let values: [[String]] }
An example API response for the second AF request:
{
"range": "'App Control'!A4:V4",
"majorDimension": "ROWS",
"values": [
[
"Bob Jones",
"A1234",
"Cathy Jones",
"1234 N. Street St. City, State 12345"
]
]
}
I saw stuff about your own callback function as a function parameter (or something along those lines) to handle this, but I was completely lost. I also looked at Swift async/await, but I don't know how that works with callback functions. Xcode had the option to refactor user.authentication.do { authentication, error in to let authentication = try await user.authentication.do(), but it threw a missing parameter error (the closure it previously had).
EDIT: user.authentication.do also returns void--another reason the refactor didn't work (I think).
There is probably a much more elegant way to do all of this so excuse the possibly atrocious way I did it.
Here is the link to Google Identity Wrapper info.
Thanks in advance for your help.
Solved my own problem.
It appears (according to Apple's async/await intro video) that when you have an unsupported callback that you need to run asynchronously, you wrap it in something called a Continuation, which allows you to manually resume the function on the thread, whether throwing or returning.
So using that code allows you to run the Google Identity token refresh with async/await.
private static func auth(_ user: GIDGoogleUser) async throws -> GIDAuthentication? {
typealias AuthContinuation = CheckedContinuation<GIDAuthentication?, Error>
return try await withCheckedThrowingContinuation { (continuation: AuthContinuation) in
user.authentication.do { authentication, error in
if let error = error {
continuation.resume(throwing: error)
} else {
continuation.resume(returning: authentication)
}
}
}
}
static func search(user: GIDGoogleUser) async throws {
// some code
guard let authentication = try await auth(user) else { ... }
// some code
}
I then ran that before using Alamofire's built-in async/await functionality for each request (here's one).
let dataTask = AF.request(...).serializingDecodable(NameResponseModel.self)
let response = try await dataTask.value
return response.values[0]

Alamofire, HTTPheaders for post request [string:any]

I need to send a post request using alamofire to my server, one of the header to be sent is not a string value but is an Int
Reading the documentation of Alamofire look like the HTTPHeaders is only type [String: String]
Is there any way to customise the HTTPHeaders to [String:Any]?
I can't find to much understandable for me online.
thanks
Alamofire doesn't have such methods, but you can easily do it
["hey": 1].mapValues { String(describing: $0) } returns [String: String]
If you have many places where you're using it, you can:
Create extension for Dictionary
extension Dictionary where Key == String, Value == Any {
func toHTTPHeaders() -> HTTPHeaders {
HTTPHeaders(mapValues { String(describing: $0) })
}
}
// Usage
AF.request(URL(fileURLWithPath: ""), headers: ["": 1].toHTTPHeaders())
Create extension for HTTPHeaders
extension HTTPHeaders: ExpressibleByDictionaryLiteral {
public init(dictionaryLiteral elements: (String, Any)...) {
self.init()
elements.forEach { update(name: $0.0, value: String(describing: $0.1)) }
}
}
// usage
AF.request(URL(fileURLWithPath: ""), headers: HTTPHeaders(["": 1]))
Create extension for Session
extension Session {
open func request(_ convertible: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: [String: Any],
interceptor: RequestInterceptor? = nil,
requestModifier: RequestModifier? = nil) -> DataRequest {
return request(convertible, method: method, parameters: parameters, encoding: encoding, headers: headers.mapValues { String(describing: $0) }, interceptor: interceptor, requestModifier: requestModifier)
}
}
// Usage
AF.request(URL(fileURLWithPath: ""), headers: ["": 1])
The reason there's no such option in Alamofire is type safety. When you use Any you can literary pass any value there and so probability of a mistake is much more. By requiring string library makes sure you're converting all values you need by yourself.
I'd go for the first variant, because it's more clear when you read the code that there's something going on there

Returning parsed JSON data using Alamofire?

Hello new to Swift and Alamofire,
The issue i'm having is when I call this fetchAllUsers() the code will return the empty users array and after it's done executing it will go inside the AF.request closure and execute the rest.
I've done some research and I was wondering is this is caused by Alamofire being an Async function.
Any suggestions?
func fetchAllUsers() -> [User] {
var users = [User]()
let allUsersUrl = baseUrl + "users/"
if let url = URL(string: allUsersUrl) {
AF.request(url).response { response in
if let data = response.data {
users = self.parse(json: data)
}
}
}
return users
}
You need to handle the asynchrony in some way. This this means passing a completion handler for the types you need. Other times it means you wrap it in other async structures, like promises or a publisher (which Alamofire also provides).
In you case, I'd suggest making your User type Decodable and allow Alamofire to do the decoding for you.
func fetchAllUsers(completionHandler: #escaping ([User]) -> Void) {
let allUsersUrl = baseUrl + "users/"
if let url = URL(string: allUsersUrl) {
AF.request(url).responseDecodable(of: [User].self) { response in
if let users = response.value {
completionHandler(users)
}
}
}
}
However, I would suggest returning the full Result from the response rather than just the [User] value, otherwise you'll miss any errors that occur.

Realm unmanaged object 'Realm accessed from incorrect thread.' Swift3

I know there are a lot discussion about 'Realm accessed from incorrect thread.', but my case a bit different, at least to my eyes...
So I have the following data structure
class User: Object, Mappable {
dynamic var name: String?
dynamic var photo: Photo?
}
class Photo: Object, Mappable {
dynamic var cover: CoverPhoto?
let photos = List<PhotoData>() // User uploaded photos, not cover
}
class CoverPhoto: Object, Mappable {
dynamic var id: String?
dynamic var user: String?
var photos = List<PhotoData>() // Different size of cover photo
}
class PhotoData : Object, Mappable {
let width = RealmOptional<Int>()
let height = RealmOptional<Int>()
dynamic var url : String?
}
I am using ObjectMapper with alamofire to map my realm objects received via rest response.
The use data is already managed and in realm db.
There is a functionality to change cover photo thus via rest receiving the new set of cover photo list and wanted to replace it.
For that reason I'm replacing it by first remove existing and appending new one.
The problem occurred when trying to access to new data which received via rest which supposed to not be a managed object, but getting exception mentioned in description.
The code which updating realm object is below and it called right after received response via alamofire, so no any DB actions in between
func updateCoverPhotos(userData: User, photo: Photo, onSuccess: ((Bool) -> Void)?, onError: ((NSError) -> Void)?) {
let userDataRef = ThreadSafeReference(to: userData)
let photos = photo.photos
DispatchQueue.global().async {
do {
let realm = try! Realm()
realm.refresh()
guard let user = realm.resolve(userDataRef) else {
return // user was deleted
}
try realm.write {
user.photo!.cover!.photos.removeAll()
user.photo!.cover!.photos.append(objectsIn: photos)
}
DispatchQueue.main.sync {
print(photoData) // Exception thrown 'Realm accessed from incorrect thread.'
onSuccess?(true)
}
} catch let error as NSError {
DispatchQueue.main.async {
onError?(error)
}
}
}
}
Could you please have a look and let me know what I'm doing wrong here ?
UPDATED
Mapping right after response, which contains new list of: PhotoData
return alamofireManager.request(url, method: .post,
parameters: parameters,
encoding: JSONEncoding.default,
headers: alamofireManager.buildHeaders())
.validate()
.responseObject(keyPath: "data") { (response: DataResponse<Photo>) in

Swift closure with Alamofire

I am making API calls to a server. I am leveraging Alamofire to handle this. I'm trying to create a function that uses Alamofire's GET function to return an object based on a custom class that holds the various outputs provided by this GET function.
It's not clear to me the way in which to do this.
Here's my custom class that will hold details about the response:
import Foundation
class ResponsePackage {
var success = false
var response: AnyObject? = nil
var error: NSError? = nil
}
In another class I have the following function:
func get(apiEndPoint: NSString) -> ResponsePackage {
let responsePackage = ResponsePackage()
Alamofire
.request(.GET, apiEndPoint)
.responseJSON {(request, response, JSON, error) in
responsePackage.response = JSON
responsePackage.success = true
responsePackage.error = error
}
return responsePackage
}
This returns nil as the call to the server is not complete before the return gets executed. I know that I should be able to do this with closures, but I am not sure how to construct this.
The code between the {} is the equivalent of block in objective-C : this is a chunk of code that gets executed asynchronously.
The error you made is where you put your return statement : when you launch your request, the code in {} is not executed until the framework received a response, so when the return statement is reached, chances are, there is still no response. You could simply move the line :
return responsePackage
inside the closure, so the func return only when it has received a response. This is a simple way, but it's not really optimal : your code will get stuck at waiting for the answers. The best way you can do this is by using closure, too. This would look something like :
func get(apiEndPoint: NSString, completion: (response: ResponsePackage) -> ()) -> Bool {
let responsePackage = ResponsePackage()
Alamofire
.request(.GET, apiEndPoint)
.responseJSON {(request, response, JSON, error) in
responsePackage.response = JSON
responsePackage.success = true
responsePackage.error = error
completion(response: responsePackage)
}
}
I make an example follow your question about responseJSON with closures:
Follow this little steps:
First of all you can create your custom types in a general class (for example a Constants.swift class):
typealias apiSuccess = (result: NSDictionary?) -> Void
typealias apiProgress = (result: NSDictionary?) -> Void // when you want to download or upload using Alamofire..
typealias apiFailure = (error: NSDictionary?) -> Void
Then in your class:
// Normal http request with JSON response..
func callJSONrequest(url:String, params:[String: AnyObject]?, success successBlock :apiSuccess,
failure failureBlock :apiFailure) {
Alamofire.request(.GET, url, parameters: params, encoding: ParameterEncoding.URL)
.responseJSON { response in
print("\(response.request?.URL)") // original URL request
//print(response.response) // URL response
//print(response.data) // server data
//print(response.result) // result of response serialization
if response.result.isSuccess {
let jsonDic = response.result.value as! NSDictionary
successBlock(result: jsonDic)
} else {
let httpError: NSError = response.result.error!
let statusCode = httpError.code
let error:NSDictionary = ["error" : httpError,"statusCode" : statusCode]
failureBlock(error: error)
}
}
}
}
func myCommonFunction() {
let myApiSuccess: apiSuccess = {(result: NSDictionary?) -> Void in
print ("Api Success : result is:\n \(result)")
// Here you can make whatever you want with result dictionary
}
let myApiFailure: apiFailure = {(error: NSDictionary?) -> Void in
print ("Api Failure : error is:\n \(error)")
// Here you can check the errors with error dictionary looking for http error type or http status code
}
var params :[String: AnyObject]?
let name : String! = "this is my name"
let id : String! = "000a"
params = ["name" : name, "id" : id]
let url : String! = "https://etc..."
callJSONrequest(url, params:params, success: myApiSuccess, failure: myApiFailure)
}