Geolocation in React Native iOS

2020-07-27 04:04发布

问题:

I am trying to access navigator.geolocation in my application.

I have also set "NSLocationWhenInUseUsageDescription" in my info.plist.

But, when I run my app, It throws an error saying "undefined is not an object (evaluating navigator.geolocation.getCurrentPosition)" .

Here is my code -

import React, { Component } from 'react';
import {
  AppRegistry,
  Image,
  ListView,
  StyleSheet,
  Text,
  Navigator,
  TouchableHighlight,
  Alert,
  TouchableOpacity,
  View
} from 'react-native';
import Spinner from 'react-native-loading-spinner-overlay'
var GiftedSpinner = require('react-native-gifted-spinner');
var GLOBAL = require('./Globals');
var stateName;
var latitude;
var longitude;

class PersonByLocationPage extends Component {

  constructor(props) {
    super(props);
    this.data = this.props.data;

     navigator.geolocation.getCurrentPosition(
                        (position) => {
                           var crd = position.coords;
                           latitude = crd.latitude;
                           longitude = crd.longitude;
                            // alert(latitude);
                            // alert(longitude);
                          },
                          (error) => alert(error.message),
                          {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
                      );


    this.REQUEST_URL = 'sample';


    this.state = {
      dataSource: new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2,
      }),
      loaded: false,
      networkError: false,
    };
  }

Can anybody tell what I am doing wrong ?

回答1:

  1. Drag RCTGeolocation.xcodeproj into the Libraries folder.
  2. Click on your project in the project navigator.
  3. Click YOUR_PROJECT_NAME under TARGETS.
  4. Click the Build Phases tab. In the Link Binary With Libraries phase,
  5. click the plus icon and select libRCTGeolocation.a from the modal list that appears.

That should be all you need. Let me know if that works for you.



回答2:

you have to add

NSLocationWhenInUseUsageDescription in Xcode

and

libRCTGeolocation.a in Xcode

you can find how to add library from http://www.slideshare.net/kobkrit/reactnative-tutorial-10-camera-roll-gallery-camera-native-modules-by-making-selfies-scoreboard-apps