React Native IOS App crashes when no network conection - ios

On the simulator it does not crash and Alerts the error, but in production it is crashes as soon as fetch request suppose to be made and it is impossible to reopen the app until network connection is back (I turn on/off airplane mode for the testing)
here are the snippets of my code
componentWillMount: function(){
NetInfo.isConnected.addEventListener('change',this.handleConnectivityChange)
NetInfo.isConnected.fetch().done((data) => {
this.setState({
isConnected: data
})
console.log('this.state.isConnected: ', this.state.isConnected);
})
},
handleConnectivityChange: function(){
var connected = this.state.isConnected ? false : true
this.setState({isConnected: connected})
console.log('this.state.isConnected11: ', this.state.isConnected);
},
....
goToList: function(replace, listview){
console.log('this.state.isConnected: ', this.props.isConnected);
if (!this.props.isConnected){
AlertIOS.alert('Error', 'Please check your network connectivity')
this.props.removeFetching()
return
}
....
fetch(url)
.then((response) => response.json())
.then((responseData) => {
....
.catch((error) => {
StatusBarIOS.setNetworkActivityIndicatorVisible(false)
AlertIOS.alert('Error', 'Please check your network connectivity')
this.props.removeFetching()
})
.done()

I spent a lot of time trying to find a way to catch exceptions when using fetch() but I was unable to get it working (e.g. using .catch() or a try/catch blog didn't work). What did work was to use XMLHttpRequest with a try/catch blog instead of fetch(). Here's an example I based off of: https://facebook.github.io/react-native/docs/network.html#using-other-networking-libraries
var request = new XMLHttpRequest();
request.onreadystatechange = (e) => {
if (request.readyState !== 4) {
return;
}
if (request.status === 200) {
console.log('success', request.responseText);
var responseJson = JSON.parse(request.responseText);
// *use responseJson here*
} else {
console.warn('error');
}
};
try {
request.open('GET', 'https://www.example.org/api/something');
request.send();
} catch (error) {
console.error(error);
}

Related

Expo Notification Error in ios [Error: Another async call to this method is in progress. Await the first Promise.]

Please provide the following:
SDK Version: "^42.0.0",
Platforms(Android/iOS/web/all): iOS
Add the appropriate "Tag" based on what Expo library you have a question on.
Hello,
[expo-notifications] Error encountered while updating server registration with latest device push token., [Error: Another async call to this method is in progress. Await the first Promise.]
This error often occurs in expo app. And always occurs in build ios app.
Using the following code:
async function registerForPushNotificationsAsync() {
let token
if (Constants.isDevice) {
const { status: existingStatus } = await Notifications.getPermissionsAsync()
let finalStatus = existingStatus
if (existingStatus !== 'granted') {
const { status } = await Notifications.requestPermissionsAsync({
ios: {
allowAlert: true,
allowBadge: true,
allowSound: true,
allowAnnouncements: true,
},
})
finalStatus = status
}
if (finalStatus !== 'granted') {
console.log('noti cancel')
return
}
// token = (await Notifications.getExpoPushTokenAsync()).data
try {
await Notifications.getExpoPushTokenAsync().then((res) => {
console.log('getExpoPUshTokenAsync >> ', res)
token = res.data
})
} catch (err) {
console.log('getExpoPushTokenAsync error >> ', err)
}
} else {
Alert.alert(
'Must use physical device for Push Notifications'
)
}
if (Platform.OS === 'android') {
Notifications.setNotificationChannelAsync('default', {
name: 'default',
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: '#FF231F7C',
})
}
return token
}
I have received a new credential, but I am still getting the error.

FetchEvent.respondWith received an error: Returned response is null

I created a pwa site which is working totally fine in android devices both online and offline. But it is throwing error FetchEvent.respondWith received an error: Returned response is null when tried to load on IOS device with safari 13.0 if the mobile device is offline.
Here is my code snippet from service_worker.js
// install event
self.addEventListener('install', evt => {
evt.waitUntil(
caches.open(staticCacheName).then((cache) => {
return cache.addAll(assets);
})
);
});
// activate event
self.addEventListener('activate', (e) => {
e.waitUntil(
caches.keys().then((keyList) => {
return Promise.all(keyList.map((key) => {
if(key !== staticCacheName) {
return caches.delete(key);
}
}));
})
);
});
//fetch event
self.addEventListener('fetch', function(event) {
event.respondWith(
fetch(event.request).catch(function() {
return caches.match(event.request,{ignoreSearch: true});
})
);
});
Please, help me find the solution.

How to delay http responses on errors in Angular 7

I am working on an Angular7 project and have some issues about error handling on http requests.
Here is my Login Component with two functions
export class LoginComponent implements OnInit, OnDestroy {
emailLogin1() {
this.authService.emailLogin1(this.loginForm.value).pipe(delay(1000)).subscribe(
(response) => {
console.log(response);
},
(error) => {
console.log(error);
}
);
}
emailLogin2() {
this.authService.emailLogin2(this.loginForm.value).pipe(delay(1000)).subscribe(
(response) => {
console.log(response);
},
(error) => {
console.log(error);
}
);
}
}
Here is my AuthService with two functions.
export class AuthService {
constructor(private http: HttpClient) {
}
emailLogin1(values): any {
return this.http.post(environment.server + '/auth/emailLogin', values).pipe(
tap(
(response) => {
localStorage.setItem('token', response['token']);
},
(error) => {
console.log(error);
}
)
);
}
emailLogin2(values): any {
return this.http.post(environment.server + '/auth/emailLogin', values).pipe(
tap(
(response) => {
localStorage.setItem('token', response['token']);
}
),
catchError((error) => {
console.log(error);
throw error;
})
);
}
}
When I make a request to the server, if response status is successful, it waits for 1000 ms and then shows the result as expected. But if response returns an error, delay(1000) function not working and error block working immediately. I tried with and without catchError. Both working exactly the same.
The delay operator will only work on events sent through the observable via "next" notifications (in your case, this is a "success"). When an error occurs, it is sent as an "error" notification, and it skips right past your delay operator. If you want to delay the error, you should catch it, introduce a delay, and then re-throw it:
emailLogin1() {
this.authService.emailLogin1(this.loginForm.value).pipe(
delay(1000), // only affects "success"
catchError(error => interval(1000).pipe( // only affects "error"
mergeMap(() => throwError(error)) // re-throw error after our delay
)),
).subscribe(
(response) => {
console.log(response);
},
(error) => {
console.log(error);
}
)
}

Ionic 2/Angular- Pinging an express server to prevent using app with no connection

My app requires being connected to our server for any use. I wrote this function in the app component to prevent the user from using the app if the server is not available
app.component.ts
pingServer(){
this.api.pingServer().subscribe(result => {
if (result.success) {
return true;
}
else {
return false
}
},
error=>{
return false;
}
);
}
}
this function just makes the request to our server, which I verified is hitting the right address
initializeApp() {
console.log("initialize");
this.platform.ready().then(() => {
console.log("platform ready");
this.screenOrientation.lock('portrait');
console.log('Orientation is ' + this.screenOrientation.type);
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
let serverAlert = this.alertCtrl.create({
title: 'Error',
subTitle: 'We are unable to reach our servers at this time. Please try again later',
buttons: ['Dismiss']
});
setTimeout(() => {
if(this.pingServer){
console.log('pinged server successfully');
this.statusBar.styleDefault();
this.splashScreen.hide();
}
else{
console.log('unable to ping server');
return serverAlert.present();
}
}, 3000);
On the server side:
router.get( '/ping', ( req, res, next ) => {
return res.json( { success: true } );
} )
This worked fine when testing on the browser. However, when using iOS it says it pings successfully every time, meanwhile, the server isn't receiving the request.

React Native NetInfo always returns offline

I'm currently trying to implement some functionality in my react native app where I use information stored locally if the device is offline, and perform a fetch if the device is online.
I used NetInfo after reading this How to handle network failure in React-Native, when network is off, but unfortunately I ran into an error where NetInfo always returns offline. I found this github issue, which recommended that I change the host in RCTReachability.m from 'htpp://apple.com' to 'apple.com'. However, I couldn't find a file with that name in the project directory. Instead I found the only mention of 'apple.com' in any file, which was in RCTNetInfo.m, which was in the correct form.
Does anybody know a way to fix this problem? Or possibly a different way to go about performing one action if the device is online, and another if the device is offline?
Here's the relevant code:
fetchData() {
NetInfo.isConnected.fetch().done((isConnected) => {
console.log('First, is ' + (isConnected ? 'online' : 'offline'));
if ( isConnected )
{
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
store.save('contacts', responseData.feed.entry)
.then(() => store.get('contacts'))
.then((contacts) => {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(contacts),
isLoading: false
});
})
})
.catch((error) => { console.error(error); });
}
else
{
store.get('contacts')
.then(contacts => {
if (contacts == null)
{
this.setState({
dataSource: this.state.dataSource.cloneWithRows(CONTACT_DATA),
isLoading: false
});
}
else
{
this.setState({
dataSource: this.state.dataSource.cloneWithRows(contacts),
isLoading: false
});
}
})
}
});
}

Resources