React-native从Camera Roll和Camera Roll API获取所有照片

时间:2016-09-09 16:56:43

标签: javascript reactjs react-native

我正在尝试使用本机CameraRoll.getPhotos API进行相机滚动照片。问题我发现文档不是很好。在react-native official documentation中,有两个术语被提及getPhotosReturnCheckergetPhotosParamChecker,我可以在其中获取有关此参数的详细信息。

我发现以下对象可以从bhwgroup blog

传递给CameraRoll.getPhotos
{
    first: ..., // (required) The number of photos wanted in reverse order of the photo application
    after: ..., // A cursor returned from a previous call to 'getPhotos'
    groupTypes: ..., // Specifies which group types to filter the results to
                     // One of ['Album', 'All', 'Event', 'Faces', 'Library', 'PhotoStream', 'SavedPhotos'(default)]
    groupName: ..., // Specifies filter on group names, like 'Recent Photos' or custom album titles
    assetType: ... // Specifies filter on assetType
                   // One of ['All', 'Videos', 'Photos'(default)]
}

根据这些,它总是需要一个参数来决定我们可以从CameraRoll获得多少张照片。相反,如果我想要相机胶卷的所有照片,我怎么能得到它?

1 个答案:

答案 0 :(得分:4)

您想要进行一些分页以访问所有照片。基本上,您将它们装入块中,并在每次获取后跟踪您停止的位置。您需要一个与此类似的州:

this.state = {
  dataSource: ds.cloneWithRows([]),
  assets: [],
  lastCursor: null,
  noMorePhotos: false,
  loadingMore: false,
};

然后获取与这些类似的功能。此示例假设您使用ListView使用ListView.DataSource

显示照片
tryPhotoLoad() {
  if (!this.state.loadingMore) {
    this.setState({ loadingMore: true }, () => { this.loadPhotos(); });
  }
}

loadPhotos() {
  const fetchParams = {
    first: 35,
    groupTypes: 'SavedPhotos',
    assetType: 'Photos',
  };

  if (Platform.OS === 'android') {
  // not supported in android
    delete fetchParams.groupTypes;
  }

  if (this.state.lastCursor) {
    fetchParams.after = this.state.lastCursor;
  }

  CameraRoll.getPhotos(fetchParams).then((data) => {
    this.appendAssets(data);
  }).catch((e) => {
    console.log(e);
  });
}

appendAssets(data) {
  const assets = data.edges;
  const nextState = {
    loadingMore: false,
  };

  if (!data.page_info.has_next_page) {
    nextState.noMorePhotos = true;
  }

  if (assets.length > 0) {
    nextState.lastCursor = data.page_info.end_cursor;
    nextState.assets = this.state.assets.concat(assets);
    nextState.dataSource = this.state.dataSource.cloneWithRows(
      _.chunk(nextState.assets, 3)
    );
  }

  this.setState(nextState);
}

endReached() {
  if (!this.state.noMorePhotos) {
    this.tryPhotoLoad();
  }
}