Cannot invoke with an argument list of type Swift 3 - arguments

Error happens here
self.iotDataManager.register(withShadow: statusThingName, eventCallback: self.deviceShadowCallback)
where
let statusThingName="TemperatureStatus"
and
func deviceShadowCallback(_ name:String!, operation:AWSIoTShadowOperationType, operationStatus:AWSIoTShadowOperationStatusType, clientToken:String!, payload:Data!) -> Void {
DispatchQueue.main.async {
//code
}
}
And signature is
self.iotDataManager.register(withShadow: <String!>, eventCallback: { (<String?>, <AWSIoTShadowOperationType>, <AWSIoTShadowOperationStatusType>, <String?>, <Data?>) in
<code>
})
I think this could be a bug in Swift , this is conversion from Swift 2 to 3 that I am trying to fix.

Declaration of the functions:
func deviceShadowCallback(
_ name: String?,
operation: AWSIoTShadowOperationType,
operationStatus: AWSIoTShadowOperationStatusType,
clientToken: String?,
payload: Data? ) {
}
func register(
withShadow: String,
eventCallback: (
String?,
AWSIoTShadowOperationType,
AWSIoTShadowOperationStatusType,
String?,
Data? ) -> Void) {
}
Execution:
let statusThingName = "status"
register(withShadow: statusThingName, eventCallback: deviceShadowCallback)
I could compile and run it without any problems.

Related

I couldn't get the Account Kit's delegate methods to get called in Swift

I'm following this tutorial to integrate Facebook AccountKit with Swift. Almost everything is working but delegate functions are not called and I don't know why this is no happening.
My code:
import UIKit
import AccountKit
class LoginViewController: UIViewController,AKFViewControllerDelegate {
//
var _accountKit: AKFAccountKit?
var _pendingLoginViewController: AKFViewController?
var _authorizationCode: String?
//
override func viewDidLoad() {
super.viewDidLoad()
if _accountKit == nil {
_accountKit = AKFAccountKit(responseType: .accessToken)
}
_pendingLoginViewController = _accountKit!.viewControllerForLoginResume()
_pendingLoginViewController?.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func prepareLoginViewController(loginViewController: AKFViewController) {
loginViewController.delegate = self
}
#IBAction func loginWithPhone(_ sender: UIButton) {
let inputState = NSUUID().uuidString
let vc: AKFViewController = _accountKit!.viewControllerForPhoneLogin(with: nil, state: inputState)
self.prepareLoginViewController(loginViewController: vc)
self.present(vc as! UIViewController, animated: true, completion: nil)
}
private func viewController(viewController: UIViewController!, didCompleteLoginWithAuthorizationCode code: String!, state: String!) {
print("1")
}
private func viewController(viewController: UIViewController!, didCompleteLoginWithAccessToken accessToken: AKFAccessToken!, state: String!) {
print("2")
}
private func viewController(viewController: UIViewController!, didFailWithError error: Error!) {
print("3")
}
private func viewControllerDidCancel(viewController: UIViewController!) {
print("4")
}
}
Swift version: 3.2
I belice is something to do with the swift version (I believe this tutorial is for 2.x) but i had a similar code from an example in Swift 3 and is working. So I don't know what is going wrong.
You don't need to cahnge methods to private.
Change delegate methods to the following:
func viewController(_ viewController: (UIViewController & AKFViewController)!,
didCompleteLoginWith accessToken: AKFAccessToken!, state: String!) {
}
func viewController(_ viewController: (UIViewController & AKFViewController)!, didCompleteLoginWithAuthorizationCode code: String!, state: String!) {
}
func viewController(_ viewController: (UIViewController & AKFViewController)!, didFailWithError error: Error!) {
}
func viewControllerDidCancel(_ viewController: (UIViewController & AKFViewController)!) {
print("canceled")
}
Problem might be that your delegate functions are all private and so the AKFViewController is unable to invoke them. Try making them public and see if you still can't get the callbacks

getting information outside of .observe method in swift Firebase

So i was able to retrieve all data from my firebase database using the following function. I was wondering if there is a way i can save the output which is "print(name)" in the self.GetUsername into a global variable
func GetUsername(uid:String , completion: #escaping ([Int]) -> ()) {
Database.database().reference().child("Songs").observeSingleEvent(of: .value) { (snapshot:DataSnapshot) in
var array: [Int] = []
for item in snapshot.children.allObjects as! [DataSnapshot]
{
array.append(item.value as! Int)
}
completion(array)
}
}
self.GetUsername(uid: (Auth.auth().currentUser?.uid)!) { (name) in
print(name)
}

How to make a CompletionHandler with Firebase Swift 3

I need to get some informations from Firebase to out it on UIViewCell. But the problem is that the function return before he get all the value. I know that's because it's asynchronous, i tried to make a completion Handler like that:
static func hardProcessingWithString(input: String, completion: #escaping (_ result: String) -> Void) {
Database.database().reference().child("Player_1").observe(.value) {
(firDataSnapshot) in
completion((firDataSnapshot.value as? String)!)
}
}
This is how i try to get the value :
var myVar: String!
hardProcessingWithString(input: "commands"){
(result: String) in
myVar = result
}
I get this error when I call the function:
Could not cast value of type '__NSDictionaryM' (0x102e292b0) to 'NSString' (0x102434c60).
Here's my Firebase database:
Or if you know how to make a Promise with Firebase let me know!
Step 1:
Create a swift file like Constant.swift. Then place the below code inside it
typealias DownloadComplete = () -> ()
Step 2:
Create a function where you want.
func hardProcessingWithString(completed: #escaping DownloadComplete) {
Database.database().reference().child("Player_1").observe (.value, with: { (firDataSnapshot) in
// put your code here
completed()
})
}
Step 3:
when you call above method in your code
hardProcessingWithString() {
// you can get the result here
}

Error "Thread 1: breakpoint 2.1"

I am working on a REST API Manager. It is giving an error and I am not able to fix it. The error I got is given below as highlighted.
import Foundation
import Alamofire
import SwiftyJSON
class RestApiManager {
var resources: JSON = [
"resources": [
"resourceA": []
]
]
let apiUrl: String
let apiUsername: String
let apiPassword: String
init(apiUrl: String, apiUsername: String, apiPassword: String) {
self.apiUrl = apiUrl
self.apiUsername = apiUsername
self.apiPassword = apiPassword
getApiResourceA() { responseObject, error in
let resourceA = JSON(responseObject!)
self.resources["resources"]["resourceA"] = resourceA
}
}
func collectDataFromApi(completionHandler: (responseObject: NSDictionary?, error: NSError?) -> ()) {
prepareHttpRequest(completionHandler)
}
func prepareHttpRequest(completionHandler: (responseObject: NSDictionary?, error: NSError?) -> ()) {
let alamofireRequest = Alamofire.request(.GET, "\(self.apiUrl)")
alamofireRequest.authenticate(user: self.apiUsername, password: self.apiPassword)
alamofireRequest.responseJSON { request, response, responseObject, error in
completionHandler(responseObject: responseObject as? NSDictionary, error: error)
}
}
func getAllResources() -> JSON {
return self.resources
}
func getApiResourceA(completion: (responseObject: NSDictionary?, error: NSError?) -> ()) {
collectDataFromApi() { responseObject, error in
completion(responseObject: responseObject, error: error)
}
}
}
And when I call this class to get the resources:
override func viewDidLoad() {
super.viewDidLoad()
if record != nil {
let url = record?.url
let username = record?.username
let password = record?.password
let restApiManager = RestApiManager(apiUrl: url!, apiUsername: username!, apiPassword: password!) // This line seems buggy
let delay = 10.0 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue()) {
let Resources = restApiManager.getAllResources()
let ResourceA = Resources["resources"]["resourceA"]
}
}
}
The line I commented prints:
Thread 1: breakpoint 2.1
I need suggestions for fix that error. Any suggestions are very much appreciated
You may have accidentally set a breakpoint without noticing.
Click and drag the blue tick representing the breakpoint outside of the gutter to erase it.
I was getting same error when I accidentally activated Breakpoint in my Xcode.
To resolve issue, simply unblock blue icon.

Closure is not constructible with

I am practicing Swift and I have the following code:
import Foundation
#objc class Model {
typealias completionBlock = (data: NSData?, error: NSError?) -> Void
func saveEmailAccount(email: String, password: String, mailServer: String, mailPort: Int, completionHandler: completionBlock) -> Void {
let httpPOSTBody = ["email" : email, "password" : password, "mailServer" : mailServer, "mailPort" : mailPort]
let urlRequest = NSMutableURLRequest()
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
urlRequest.HTTPMethod = "POST"
urlRequest.HTTPBody = NSJSONSerialization.dataWithJSONObject(httpPOSTBody, options: nil, error: nil)
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
session.dataTaskWithURL(urlRequest.URL!, completionHandler: { (data: NSData!, response:NSURLResponse!, error: NSError!) -> Void in
completionBlock(data, error)
})
}
}
But I am getting "completionBlock is not constructible with '(NSData!, NSError!)'. Not sure what I'm doing wrong
You're trying to invoke completionHandler with the typo completionBlock Change the block invocation from:
completionBlock(data, error)
to:
completionHandler(data, error)
One reason why Apple suggests (and I concur) that type names should start with caps and variable names with lower case.
The other problem is that by defining the type alias as:
typealias completionBlock = (data: NSData?, error: NSError?) -> Void
You are specifying that the completion block should be defined and called with named parameters:
completionHandler(data:data, error:error)
Or, change the type alias to:
typealias completionBlock = (NSData?, NSError?) -> Void
Which would be more inline with the norms I've seen.

Resources