I have a button and when I press it I´m calling an Async function:
func check(url : String){
let url = NSURL(string: url)
print("Checking")
dispatch_async(dispatch_get_main_queue(), {
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
if error == nil {
self.isWorking = true
}
else{
self.isWorking = false
}
}
}
task.resume()
})
}
So when I press my button I do the following:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!){
let web = segue.destinationViewController as! ViewController()
check(url)
dispatch_async(dispatch_get_main_queue(), {
if (isWorking){
// Do stuff
}
})
}
The problem is that isWorking is called before the check method is completed.
How can I make sure that check is completed before I make my check for isWorking?
You could use a "completion handler":
func check(url : String, completion: (isWorking: Bool)->()) {
let url = NSURL(string: url)
print("Checking")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
if error == nil {
completion(isWorking: true)
}
else{
completion(isWorking: false)
}
}
task.resume()
}
And you call it like this, with a trailing closure:
check(url) { (isWorking) in
if isWorking {
// do stuff
} else {
// not working
}
}
This will do the job:
import UIKit
class AnyViewController: UIViewController
{
var isWorking = false
func check(url : String)
{
let url = NSURL(string: url)
print("Checking")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
if error == nil
{
self.performSegueWithIdentifier("mySegueID", sender: nil)
}
else{
self.isWorking = false
}
}
task.resume()
}
}
You can post a notification to a listener to perform the segue only when the task is complete with NSNotificationCenter.defaultCenter().postNotificationName("name", object: nil):
override func viewDidLoad() {
super.viewDidLoad()
// Register a notification listener
NSNotificationCenter.defaultCenter().addObserver(self, selector: "customSegue:", name:"segue", object: nil)
}
func customSegue(notification: NSNotification){
// Do stuff
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!){
check(url)
}
func check(url : String){
let url = NSURL(string: url)
print("Checking")
dispatch_async(dispatch_get_main_queue(), {
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
if error == nil {
self.isWorking = true
// Send a notification to the listener to perform stuff
NSNotificationCenter.defaultCenter().postNotificationName("segue", object: nil)
}
else{
self.isWorking = false
}
}
}
task.resume()
})
}
This way the code in customSegue func will only be executed when error == nil
Related
I'm a new Flutter user, here I want to explain my problem, I have a problem when I want to update data, the data can't be entered into the database, there is an error when I send data to the database.
Is there something wrong with my logic code on flutter ? Here's my source snippet
API.DART
updateData(apiURL, id, body ) async {
var fullUrl = _url + apiURL + '/' + id.toString();
await _getToken();
return await http.put(
fullUrl,
headers: _setHeaders(),
body: json.encode(body),
);
}
Nasabah_service.dart
static Future<List<Nasabah>> updateUser(id) async {
Map<String, String> data;
final response = await Network().updateData(baseUrl, id, data,);
List<Nasabah> list = parseResponse(response.body);
return list;
}
Here's the update function on the formfield
void _update() async {
setState(() {
_isLoading = true;
});
var data = {
"nama_debitur" : _nama_debiturController.text,
"alamat" : _alamatController.text,
"no_telp" : _no_telpController.text,
"no_ktp" : _no_ktpController.text,
"no_selular" : _no_selularController.text
};
print(data);
var res = await Network().updateData(NasabahService.baseUrl, 'mstdebitur' , data);
var body = json.decode(res.body);
if (res.statusCode == 200) {
SharedPreferences localStorage = await SharedPreferences.getInstance();
localStorage.setString('mstdebitur', json.encode(body['mstdebitur']));
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('Berhasil Disimpan'),
duration: Duration(seconds: 2),
));
} else {
// if (body['message']['nama_debitur'] != null) {
// _showMsg(body['message']['nama_debitur'][0].toString());
// } else if (body['message']['alamat'] != null) {
// _showMsg(body['message']['alamat'][0].toString());
// } else if (body['message']['no_telp'] != null) {
// _showMsg(body['message']['no_telp'][0].toString());
// }
// else if (body['message']['no_ktp'] != null) {
// _showMsg(body['message']['no_ktp'][0].toString());
// }
// else if (body['message']['no_selular'] != null) {
// _showMsg(body['message']['no_selular'][0].toString());
// }
// ScaffoldMessenger.of(context)
// .showSnackBar(new SnackBar(content: Text("Gagal")));
}
setState(() {
_isLoading = false;
});
}
}
I'm checking, if a given user is part of a group by this code below. I'm getting
unauthorized exception
(0x80070005)
and I do not understand why? I'm using SPSecurity.RunWithElevatedPrivileges, so why it is giving me this exception!? Anybody a hint for me? Thanks in advance!
public bool IsUserInGroup(SPWeb web, string groupName, string user)
{
try
{
bool returnValue = false;
SPSecurity.RunWithElevatedPrivileges(() =>
{
if (web.Groups.OfType<SPGroup>().Where(g => g.Name == groupName).Count() > 0)
{
SPGroup spGroup = web.Groups[groupName];
if (spGroup.Users.OfType<SPUser>().Where(u => u.LoginName.Equals(user)).Count() > 0)
{
returnValue = true;
}
else
{
returnValue = false;
}
}
else
{
returnValue = false;
}
});
return returnValue;
}
catch (Exception exp)
{
Classes.Logs.Error.Log_Error("IsUserInGroup", "DocumentCenterItem.cs", exp.Message, DateTime.Now);
return false;
}
}
You need to create a new instance of SP Web inside elevated privileges. In your current implementation, you are reusing the web object which runs in current user context.
So, try and modify the below code as per your requirement :
public bool IsUserInGroup(SPWeb web, string groupName, string user)
{
try
{
bool returnValue = false;
SPSecurity.RunWithElevatedPrivileges(() =>
{
using(SPSite site = new SPSite(web.Site.ID))
{
using(SPWeb elevatedWeb = site.OpenWeb(web.ID))
{
if (elevatedWeb.Groups.OfType<SPGroup>().Where(g => g.Name == groupName).Count() > 0)
{
SPGroup spGroup = elevatedWeb.Groups[groupName];
if (spGroup.Users.OfType<SPUser>().Where(u => u.LoginName.Equals(user)).Count() > 0)
{
returnValue = true;
}
else
{
returnValue = false;
}
}
else
{
returnValue = false;
}
}
}
});
return returnValue;
}
catch (Exception exp)
{
Classes.Logs.Error.Log_Error("IsUserInGroup", "DocumentCenterItem.cs", exp.Message, DateTime.Now);
return false;
}
}
/* global FB */
"use strict";
/*
* #author Ally Ogilvie
* #copyright Wizcorp Inc. [ Incorporated Wizards ] 2014
* #file - facebookConnectPlugin.js
* #about - JavaScript interface for PhoneGap bridge to Facebook Connect SDK
*
*
*/
if (!window.cordova) {
// This should override the existing facebookConnectPlugin object created from cordova_plugins.js
var facebookConnectPlugin = {
getLoginStatus: function (s, f) {
// Try will catch errors when SDK has not been init
try {
FB.getLoginStatus(function (response) {
s(response);
});
} catch (error) {
if (!f) {
console.error(error.message);
} else {
f(error.message);
}
}
},
showDialog: function (options, s, f) {
if (!options.name) {
options.name = "";
}
if (!options.message) {
options.message = "";
}
if (!options.caption) {
options.caption = "";
}
if (!options.description) {
options.description = "";
}
if (!options.href) {
options.href = "";
}
if (!options.picture) {
options.picture = "";
}
// Try will catch errors when SDK has not been init
try {
FB.ui({
method: options.method,
message: options.message,
name: options.name,
caption: options.caption,
description: (
options.description
),
href: options.href,
picture: options.picture
},
function (response) {
if (response && (response.request || !response.error_code)) {
s(response);
} else {
f(response);
}
});
} catch (error) {
if (!f) {
console.error(error.message);
} else {
f(error.message);
}
}
},
// Attach this to a UI element, this requires user interaction.
login: function (permissions, s, f) {
// JS SDK takes an object here but the native SDKs use array.
var permissionObj = {};
if (permissions && permissions.length > 0) {
permissionObj.scope = permissions.toString();
}
FB.login(function (response) {
if (response.authResponse) {
s(response);
} else {
f(response.status);
}
}, permissionObj);
},
getAccessToken: function (s, f) {
var response = FB.getAccessToken();
if (!response) {
if (!f) {
console.error("NO_TOKEN");
} else {
f("NO_TOKEN");
}
} else {
s(response);
}
},
logEvent: function (eventName, params, valueToSum, s, f) {
// AppEvents are not avaliable in JS.
s();
},
logPurchase: function (value, currency, s, f) {
// AppEvents are not avaliable in JS.
s();
},
logout: function (s, f) {
// Try will catch errors when SDK has not been init
try {
FB.logout( function (response) {
s(response);
});
} catch (error) {
if (!f) {
console.error(error.message);
} else {
f(error.message);
}
}
},
api: function (graphPath, permissions, s, f) {
// JS API does not take additional permissions
// Try will catch errors when SDK has not been init
try {
FB.api(graphPath, function (response) {
if (response.error) {
f(response);
} else {
s(response);
}
});
} catch (error) {
if (!f) {
console.error(error.message);
} else {
f(error.message);
}
}
},
// Browser wrapper API ONLY
browserInit: function (appId, version) {
if (!version) {
version = "v2.0";
}
FB.init({
appId : appId,
cookie : true,
xfbml : true,
version : version
})
}
};
// Bake in the JS SDK
(function () {
if (!window.FB) {
console.log("launching FB SDK");
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/sdk.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}
}());
}
I'm having error of FB not Defined when I try login with facebook in my code and gives error in above js file that FB is not Defined.
In Swift, how can one check if a string is a valid double value? I have been using the following extension from this question (but as a float) but if the value cannot be converted, it simply returns "0":
extension String {
var doubleValue:Double? {
return (self as NSString).doubleValue
}
}
Ideally, I would like it to return nil so it can be caught in an if-let, like so:
if let i = str.doubleValue {
object.price = i
} else {
// Tell user the value is invalid
}
edit/update: Xcode 11 or later • Swift 5.1 or later
You can use Double initializer init?<S>(_ text: S) where S : StringProtocol to create an instance property on StringProtocol and use it to check if a String or Substring is a valid Double:
extension StringProtocol {
var double: Double? { Double(self) }
var float: Float? { Float(self) }
var integer: Int? { Int(self) }
}
Testing
let str = "2.9"
if let value = str.double {
print(value) // "2.9\n"
} else {
print("invalid input")
}
str.prefix(1).integer // 2
str.suffix(1).integer // 9
It is indeed more efficient not to create a number formatter every time we do a conversion:
extension String {
struct NumFormatter {
static let instance = NumberFormatter()
}
var doubleValue: Double? {
return NumFormatter.instance.number(from: self)?.doubleValue
}
var integerValue: Int? {
return NumFormatter.instance.number(from: self)?.intValue
}
}
Why not let it return false? Or true of course.
extension String {
func isInt() -> Bool {
if let intValue = Int(self) {
return true
}
return false
}
func isFloat() -> Bool {
if let floatValue = Float(self) {
return true
}
return false
}
func isDouble() -> Bool {
if let doubleValue = Double(self) {
return true
}
return false
}
func numberOfCharacters() -> Int {
return self.characters.count
}
}
Or even better, as suggested by #LeoDabus:
extension String {
var isInteger: Bool { return Int(self) != nil }
var isFloat: Bool { return Float(self) != nil }
var isDouble: Bool { return Double(self) != nil }
}
Here is my function:
func je_numerik(text:Character)->Bool //en znak
{
if((text=="0")||(text=="1")||(text=="2")||(text=="3")||(text=="4")||(text=="5")||(text=="6")||(text=="7")||(text=="8")||(text=="9")){
return true
}
else
{
return false
}
}
func je_stevilka(text: String)->Bool
{
var pika:Character
pika="."
var je_stevilka=true
//var znaki = Character(text)
var znaki=Array(text)
var stevilo_znakov=znaki.count
if(stevilo_znakov==0)
{
je_stevilka=false
}
else
{
if(stevilo_znakov==1)
{
if(je_numerik(znaki[0]))
{
je_stevilka=true
}
else
{
je_stevilka=false
}
}
else
{
if((je_numerik(znaki[0])) && (!((znaki[0]=="0")&&((znaki[1]=="0"))))&&(!((znaki[0]=="0")&&((je_numerik(znaki[1]))))))
{
var je_pika=false
for var i = 0; i < stevilo_znakov; i++
{
if(je_numerik(znaki[i])||(znaki[i]==pika))
{
if(znaki[i]==pika)
{
if(je_pika)
{
je_stevilka=false
}
else
{
je_pika=true
if(stevilo_znakov==(i+1))
{
je_stevilka=false
}
}
}
}
else
{
je_stevilka=false
}
}
}
else
{
je_stevilka=false
}
}
}
return je_stevilka
}
Just call it like this:
var check_if_is_number=je_stevilka(numberText)
How can we display login page in Ajax popup box on homepage load in Magento that to popup box need to come only one time until browser is closed and i also need to place FB connect to same popup box .can any reply me soon please
Hi you can use any lightbox plugin to display the code, and to show login in popup you can override the customer AccountController.php like this
protected $_validActions = array('create','login','logoutSuccess','forgotpassword','forgotpasswordpost','confirm','confirmation','resetpassword','resetpasswordpost');
protected $_customActions = array('signupformpopup','ajaxLogin','ajaxCreate');
public function preDispatch()
{
// a brute-force protection here would be nice
$action = $this->getRequest()->getActionName();
if (preg_match('/^('.$this->_getCustomActions().')/i', $action))
{
$this->getRequest()->setActionName($this->_validActions[1]);
}
parent::preDispatch();
if ($action != $this->getRequest()->getActionName())
{
$this->getRequest()->setActionName($action);
}
if (!$this->getRequest()->isDispatched()) {
return;
}
if (!preg_match('/^('.$this->_getValidActions().')/i', $action)) {
if (!$this->_getSession()->authenticate($this)) {
$this->setFlag('', 'no-dispatch', true);
}
} else {
$this->_getSession()->setNoReferer(true);
}
}
protected function _getValidActions()
{
return implode("|", array_merge($this->_validActions, $this->_customActions));
}
protected function _getCustomActions()
{
return implode("|", $this->_customActions);
}
/**
* Login post action
*/
public function ajaxLoginAction() {
if ($this->_getSession()->isLoggedIn()) {
$this->_redirect('*/*/');
return;
}
$session = $this->_getSession();
$result=array();
if ($this->getRequest()->isPost()) {
$login = $this->getRequest()->getPost('login');
if (!empty($login['username']) && !empty($login['password'])) {
try {
$session->login($login['username'], $login['password']);
if ($session->getCustomer()->getIsJustConfirmed()) {
$this->_welcomeCustomer($session->getCustomer(), true);
}
$result['success'] = true;
$result['redirecturl'] = Mage::getUrl('customer/account/edit');
} catch (Mage_Core_Exception $e) {
switch ($e->getCode()) {
case Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED:
/*$message = Mage::helper('customer')->__('This account is not confirmed. Click here to resend confirmation email.', Mage::helper('customer')->getEmailConfirmationUrl($login['username']));*/
$result['success'] = false;
$result['message'] = Mage::helper('customer')->__('This account is not confirmed.');
break;
case Mage_Customer_Model_Customer::EXCEPTION_INVALID_EMAIL_OR_PASSWORD:
$message = $e->getMessage();
$result['success'] = false;
$result['message'] = Mage::helper('customer')->__($message);
break;
default:
$message = $e->getMessage();
$result['success'] = false;
$result['message'] = Mage::helper('customer')->__($message);
}
//$session->addError($message);
$session->setUsername($login['username']);
} catch (Exception $e) {
// Mage::logException($e); // PA DSS violation: this exception log can disclose customer password
}
} else {
//$session->addError($this->__('Login and password are required.'));
$result['success'] = false;
$result['message'] = Mage::helper('customer')->__('Login and password are required.');
}
}
$this->getResponse()->setBody(Zend_Json::encode($result));
//$this->_loginPostRedirect();
}
/**
* Login post action
*/
public function ajaxCreateAction()
{
$session = $this->_getSession();
if ($session->isLoggedIn()) {
$this->_redirect('*/*/');
return;
}
$session->setEscapeMessages(true); // prevent XSS injection in user input
if ($this->getRequest()->isPost()) {
$errors = array();
if (!$customer = Mage::registry('current_customer')) {
$customer = Mage::getModel('customer/customer')->setId(null);
}
/* #var $customerForm Mage_Customer_Model_Form */
$customerForm = Mage::getModel('customer/form');
$customerForm->setFormCode('customer_account_create')
->setEntity($customer);
$customerData = $customerForm->extractData($this->getRequest());
if ($this->getRequest()->getParam('is_subscribed', false)) {
$customer->setIsSubscribed(1);
}
/**
* Initialize customer group id
*/
$customer->getGroupId();
if ($this->getRequest()->getPost('create_address')) {
/* #var $address Mage_Customer_Model_Address */
$address = Mage::getModel('customer/address');
/* #var $addressForm Mage_Customer_Model_Form */
$addressForm = Mage::getModel('customer/form');
$addressForm->setFormCode('customer_register_address')
->setEntity($address);
$addressData = $addressForm->extractData($this->getRequest(), 'address', false);
$addressErrors = $addressForm->validateData($addressData);
if ($addressErrors === true) {
$address->setId(null)
->setIsDefaultBilling($this->getRequest()->getParam('default_billing', false))
->setIsDefaultShipping($this->getRequest()->getParam('default_shipping', false));
$addressForm->compactData($addressData);
$customer->addAddress($address);
$addressErrors = $address->validate();
if (is_array($addressErrors)) {
$errors = array_merge($errors, $addressErrors);
}
} else {
$errors = array_merge($errors, $addressErrors);
}
}
try {
$customerErrors = $customerForm->validateData($customerData);
if ($customerErrors !== true) {
$errors = array_merge($customerErrors, $errors);
} else {
$customerForm->compactData($customerData);
$customer->setPassword($this->getRequest()->getPost('password'));
$customer->setConfirmation($this->getRequest()->getPost('confirmation'));
$customerErrors = $customer->validate();
if (is_array($customerErrors)) {
$errors = array_merge($customerErrors, $errors);
}
}
$validationResult = count($errors) == 0;
$result = array();
if (true === $validationResult) {
$customer->save();
if ($customer->isConfirmationRequired()) {
$customer->sendNewAccountEmail('confirmation', $session->getBeforeAuthUrl());
// $session->addSuccess($this->__('Account confirmation is required. Please, check your email for the confirmation link. To resend the confirmation email please click here.', Mage::helper('customer')->getEmailConfirmationUrl($customer->getEmail())));
//$this->_redirectSuccess(Mage::getUrl('*/*/index', array('_secure'=>true)));
//return;
$result['success'] = true;
$result['message'] = $this->__('Account confirmation is required. Please, check your email for the confirmation link. To resend the confirmation email please click here.', Mage::helper('customer')->getEmailConfirmationUrl($customer->getEmail()));
} else {
$session->setCustomerAsLoggedIn($customer);
$url = $this->_welcomeCustomer($customer);
//$this->_redirectSuccess($url);
//return;
$result['success'] = true;
$result['message'] = $this->__('You are successfully registered');
}
} else {
$session->setCustomerFormData($this->getRequest()->getPost());
if (is_array($errors)) {
$result['success'] = false;
foreach ($errors as $errorMessage) {
//$session->addError($errorMessage);
$result['message'] .= $errorMessage;
}
} else {
//$session->addError($this->__('Invalid customer data'));
$result['success'] = false;
$result['message'] = $this->__('Invalid customer data');
}
}
} catch (Mage_Core_Exception $e) {
$session->setCustomerFormData($this->getRequest()->getPost());
if ($e->getCode() === Mage_Customer_Model_Customer::EXCEPTION_EMAIL_EXISTS) {
$url = Mage::getUrl('customer/account/forgotpassword');
$result['success'] = false;
$result['message'] = $this->__('There is already an account with this email address. If you are sure that it is your email address.');
} else {
$result['success'] = false;
$result['message'] = $e->getMessage();
}
//$session->addError($message);
} catch (Exception $e) {
// $session->setCustomerFormData($this->getRequest()->getPost())
// ->addException($e, $this->__('Cannot save the customer.'));
$result['success'] = false;
$result['message'] = $this->__('Cannot save the customer.');
}
}
//$this->_redirectError(Mage::getUrl('*/*/create', array('_secure' => true)));
$this->getResponse()->setBody(Zend_Json::encode($result));
}
}