In obj-c I can get the temprature from a beacon with this block :
- (void)readTemperatureWithCompletion:(ESTNumberCompletionBlock)completion
How can I do this with SWIFT with a closure. I have been studying closures but still not sure how to run this block in SWIFT.
Can anyone advise ?
Thanks
This worked for me:
func beaconConnectionDidSucceeded(beacon: ESTBeacon) {
NSLog("beaconConnectionDidSucceeded")
beacon.readTemperatureWithCompletion() { value, error in
NSLog("readTemperatureWithCompletion, value = \(value), error = \(error)")
}
}
I believe this is more correct
beacon.readTemperatureWithCompletion({(temp:NSNumber!, error:NSError?) -> () in
if error? == nil{
println("\(temp)")
}else
{
println("Error \(error!.description)")
}
})
Related
I know the idiomatic way to handle errors in rust is using match statement but I am looking for other ways to do the same.
use std::fs;
fn main() {
if let Ok(f) = fs::read_dir("/dummy"){
println!("First: {:?}", f);
}else{
println!("Error");
}
}
This works but I need the original Result error from fs::read_dir("/dummy") to be printed in the else statement. How can I do it?
Generally, I'd consider such an approach a bad idea, but you do have a few options, the most obvious two being "multiple if lets" and a "functional style" approach. I've included the match version for comparison. The code is available on the playground.
fn multiple_if_lets() {
let f = std::fs::read_dir("/dummy");
if let Ok(f) = &f {
println!("First: {:?}", f);
}
if let Err(f) = &f {
println!("Error: {:?}", f);
}
}
fn functional_style() {
std::fs::read_dir("/dummy")
.map(|f| println!("First: {:?}", f))
.unwrap_or_else(|f| println!("Error: {:?}", f));
}
fn match_style() {
match std::fs::read_dir("/dummy") {
Ok(f) => println!("First: {:?}", f),
Err(f) => println!("Error: {:?}", f),
}
}
I'm not quite sure why you don't want to use match because it is like a better if let! But you might find it useful to use an external crate like anyhow. You can very easily propagate all errors as one type and also add context where it makes sense.
In your Cargo.toml
[dependencies]
anyhow = "1"
In your code
use std::fs;
use anyhow::Context;
fn main() -> anyhow::Result<()> {
let dir = fs::read_dir("/dummy").context("failed to read dir")?;
// another fallible function which can return a `Result` with a
// different error type.
do_something(dir).context("failed to do something")?;
Ok(())
}
If read_dir had to fail here your program would exit and it would output the following
Error: failed to read dir
Caused by:
No such file or directory (os error 2)
If you wanted to throw away the error but still print it out you could still use match.
let dir = match fs::read_dir("/dummy").context("failed to read dir") {
Ok(dir) => Some(dir),
Err(err) => {
eprintln!("Error: {:?}", err);
None
}
};
This would output something like the following but still continue:
Error: failed to read dir
Caused by:
No such file or directory (os error 2)
Since Rust 1.65.0 (Nov. 2022), as mentioned by Mara Bos, you can do:
let Ok(f) = fs::read_dir("/dummy") else{ println!("Error"); return };
println!("First: {:?}", f);
let-else statements.
You can now write things like:
let Ok(a) = i32::from_str("123") else { return };
without needing an if or match statement.
This can be useful to avoid deeply nested if statements.
When wrong user login ios app is crashing and no log displayed. But in Android is working with out crash. Why?
Thread 26: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Fatal error: Unexpectedly found nil while unwrapping an Optional value: file /Users/user/FlutterHome/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_aws_amplify_cognito-1.0.0+7/ios/Classes/SwiftFlutterAwsAmplifyCognito.swift, line 275
Future<dynamic> login(
{String username,
String password,
GlobalKey<ScaffoldState> globalKey}) async {
return FlutterAwsAmplifyCognito.signIn(username, password)
.then((SignInResult result) {
debugPrint('------------------------${result}');
switch (result.signInState) {
case SignInState.SMS_MFA:
// TODO: Handle this case.
break;
case SignInState.PASSWORD_VERIFIER:
// TODO: Handle this case.
break;
case SignInState.CUSTOM_CHALLENGE:
// TODO: Handle this case.
break;
case SignInState.DEVICE_SRP_AUTH:
// TODO: Handle this case.
break;
case SignInState.DEVICE_PASSWORD_VERIFIER:
// TODO: Handle this case.
break;
case SignInState.ADMIN_NO_SRP_AUTH:
// TODO: Handle this case.
break;
case SignInState.NEW_PASSWORD_REQUIRED:
// TODO: Handle this case.
break;
case SignInState.DONE:
break;
case SignInState.UNKNOWN:
// TODO: Handle this case.
break;
case SignInState.ERROR:
// TODO: Handle this case.
break;
}
return result.codeDetails;
}).catchError((error) {
if (error.code == 'Error') {
globalKey.currentState.showSnackBar(SnackBar(
backgroundColor: Colors.red,
content: Text(LocalizationsUtils(
Locale.fromSubtags(languageCode: AppPreferences().language))
.errorIncorrectEmailPassword),
));
}
});
}
github link
https://github.com/jonsaw/amazon-cognito-identity-dart
Had the same problem. There is just a missing return in code.
static func signIn(result: #escaping FlutterResult, username: String, password: String) {
AWSMobileClient.default().signIn(username: username, password: password){(signinResult, error) in
if (error != nil) {
DispatchQueue.main.async {
result(FlutterError(code: "Error", message: "Error signing in", details: error?.localizedDescription))
}
return // this return was missing!!!
}
FYI: If you run the Application with Xcode, the debugger will point you to the bug.
PS: the return is missing in every error, so the app might crash on other functionCalls too, for example if you try to get Tokens without being loggedIn.
I want to pass data from my iOS App to my watchOS 3 app using WKWatchConnectivityRefreshBackgroundTask
How do I set up code in my watchOS App to handle the data being transferred?
For example in the past I used this iOS code to send a message from the iOS App and if there was no connection send a context:
func sendTable()
{
let tableInfo: WatchWorkout = PhoneData().buildWatchTableData(Foundation.Date().refDays())
let archivedTable: Data = NSKeyedArchiver.archivedData(withRootObject: tableInfo)
if validSession
{
sendMessage([Keys.UpdateType : PhoneUpdateType.TableInfo.rawValue, Keys.Workout: archivedTable])
}
else
{
do
{
try updateApplicationContext([Keys.UpdateType : PhoneUpdateType.TableInfo.rawValue, Keys.Workout: archivedTable])
}
catch
{
print("Phone Session - error sending info: \(error)")
}
}
}
func sendMessage(_ message: [String : AnyObject], replyHandler: (([String : AnyObject]) -> Void)? = nil, errorHandler: ((NSError) -> Void)? = nil)
{
print("Phone Session - phone sent message")
session!.sendMessage(message,
replyHandler:
nil,
errorHandler:
{
(error) -> Void in
print("Phone Session - Error Message during transfer to Watch: \(error)")
}
)
}
func updateApplicationContext(_ applicationContext: [String : AnyObject]) throws
{
print("Phone Session - phone sent context")
if ((session) != nil)
{
do
{
try session!.updateApplicationContext(applicationContext)
}
catch let error
{
print("Phone Session - OPPS something wrong - context send failed")
throw error
}
}
}
I'm not sure how to code the receipt of this data as a background task on the watch.
Can someone provide some example code or post a link? The only Apple example code is not very helpful:
https://developer.apple.com/library/prerelease/content/samplecode/WatchBackgroundRefresh/Introduction/Intro.html
Thanks
Greg
The Quick Switch sample code was updated together with the release of watchOS 3 to include an example of handling the WatchConnectivity background refresh task.
#ccjensen The Quick Switch sample code doesn't work, is it?
It will crash on my iPhone6 iOS10.0 beta3. I sent feedback already last Friday.
In my Case, calling
updateApplicationContext(_:)
transferUserInfo(_:)
transferCurrentComplicationUserInfo(_:)
transferFile(_:metadata:)
on iPhone side never trigger handle(_:) listener.
I'm trying to get the changed value of a HTML-Node.
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if(mutation.addedNodes[0].data == "9"){
dostuff();
}
}
}
But javascript returns only an object and no array of
addedNodes.mutation.addedNodes[0]
prints out:
<TextNode textContent="9">
Where can I get the value of the changed HTML-Node?
Thanks alot.
Ok, found a solution via Stackoverflow
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
[].call(mutation.addedNodes).forEach(function (addedNode) {
if(addedNode.textContent == "9"){
dostuff();
}
});
});
});
I'm new to xcode. I would like to convert below objective c code to swift equivalent.
ActionStringCancelBlock cancel = ^(ActionSheetStringPicker *picker) {
NSLog(#"Block Picker Canceled");
};
Thanks in advance.
This is the swift equivalent:
let cancel: ActionStringCancelBlock = { (picker: ActionSheetStringPicker) in
NSLog("Block Picker Canceled")
}
Suggested reading: Closures
You can probably just do:
let cancel: ActionStringCancelBlock = { (picker: ActionSheetStringPicker!) in
println("Block Picker Canceled")
return
}
but you might get away with:
let cancel: ActionStringCancelBlock = {
println("Block Picker Canceled")
}