Skip to content

API Reference

uni-app provides a rich set of API interfaces that allow developers to call various device functions and platform services. This section will detail the usage of various types of APIs.

API Categories

Basic APIs

Network Requests

  • uni.request() - Make network requests
  • uni.uploadFile() - Upload files
  • uni.downloadFile() - Download files
  • uni.connectSocket() - Create WebSocket connection

Data Storage

  • uni.setStorage() - Asynchronously store data
  • uni.setStorageSync() - Synchronously store data
  • uni.getStorage() - Asynchronously get data
  • uni.getStorageSync() - Synchronously get data
  • uni.removeStorage() - Asynchronously remove data
  • uni.clearStorage() - Clear local data

Interface APIs

Interactive Feedback

  • uni.showToast() - Show message toast
  • uni.showLoading() - Show loading dialog
  • uni.hideLoading() - Hide loading dialog
  • uni.showModal() - Show modal dialog
  • uni.showActionSheet() - Show action sheet
  • uni.setNavigationBarTitle() - Set navigation bar title
  • uni.setNavigationBarColor() - Set navigation bar color
  • uni.showNavigationBarLoading() - Show navigation bar loading animation
  • uni.hideNavigationBarLoading() - Hide navigation bar loading animation

Background

  • uni.setBackgroundColor() - Set window background color
  • uni.setBackgroundTextStyle() - Set pull-down background text style

Routing APIs

  • uni.navigateTo() - Keep current page and navigate to a page within the app
  • uni.redirectTo() - Close current page and navigate to a page within the app
  • uni.reLaunch() - Close all pages and open a page within the app
  • uni.switchTab() - Jump to tabBar page
  • uni.navigateBack() - Close current page and return to previous page

Device APIs

System Information

  • uni.getSystemInfo() - Get system information
  • uni.getSystemInfoSync() - Synchronously get system information
  • uni.canIUse() - Check if APIs, callbacks, parameters, components are available in current version

Network Status

  • uni.getNetworkType() - Get network type
  • uni.onNetworkStatusChange() - Listen for network status changes

Accelerometer

  • uni.onAccelerometerChange() - Listen for accelerometer data
  • uni.startAccelerometer() - Start listening for accelerometer data
  • uni.stopAccelerometer() - Stop listening for accelerometer data

Compass

  • uni.onCompassChange() - Listen for compass data
  • uni.startCompass() - Start listening for compass data
  • uni.stopCompass() - Stop listening for compass data

Media APIs

Images

  • uni.chooseImage() - Choose images from local album or take photos with camera
  • uni.previewImage() - Preview images
  • uni.getImageInfo() - Get image information
  • uni.saveImageToPhotosAlbum() - Save image to system album

Recording

  • uni.startRecord() - Start recording
  • uni.stopRecord() - Stop recording

Audio Playback Control

  • uni.playVoice() - Start playing voice
  • uni.pauseVoice() - Pause playing voice
  • uni.stopVoice() - Stop playing voice

Music Playback Control

  • uni.getBackgroundAudioManager() - Get globally unique background audio manager
  • uni.createAudioContext() - Create and return audio context audioContext object

Video

  • uni.chooseVideo() - Record video or choose video from phone album
  • uni.saveVideoToPhotosAlbum() - Save video to system album
  • uni.createVideoContext() - Create and return video context videoContext object

Location APIs

Get Location

  • uni.getLocation() - Get current geographic location and speed
  • uni.chooseLocation() - Open map to choose location

View Location

  • uni.openLocation() - View location using built-in map

File APIs

File Management

  • uni.saveFile() - Save file locally
  • uni.getSavedFileList() - Get list of locally saved files
  • uni.getSavedFileInfo() - Get file information of local files
  • uni.removeSavedFile() - Delete locally stored files
  • uni.openDocument() - Open document in new page

Drawing APIs

Canvas

  • uni.createCanvasContext() - Create canvas drawing context
  • uni.canvasToTempFilePath() - Export specified area of current canvas to generate image of specified size
  • uni.canvasGetImageData() - Return array describing pixel data of canvas area
  • uni.canvasPutImageData() - Draw pixel data to canvas

Third-party Platform APIs

Login

  • uni.login() - Call interface to get login credentials
  • uni.checkSession() - Check if login status has expired

Authorization

  • uni.authorize() - Request authorization from user in advance
  • uni.getSetting() - Get user's current settings

User Information

  • uni.getUserInfo() - Get user information

WeChat Payment

  • uni.requestPayment() - Initiate WeChat payment

Template Messages

  • uni.addTemplate() - Combine template and add to personal template library
  • uni.deleteTemplate() - Delete a template from account
  • uni.getTemplateLibraryById() - Get keyword library for template title in template library
  • uni.getTemplateLibraryList() - Get list of mini program template library titles
  • uni.getTemplateList() - Get list of existing templates in account
  • uni.sendTemplateMessage() - Send template message

API Usage Examples

Network Request Examples

javascript
// Make GET request
uni.request({
  url: 'https://api.example.com/data',
  method: 'GET',
  data: {
    id: 1
  },
  success: (res) => {
    console.log('Request successful', res.data)
  },
  fail: (err) => {
    console.error('Request failed', err)
  }
})

// Make POST request
uni.request({
  url: 'https://api.example.com/submit',
  method: 'POST',
  data: {
    name: 'John Doe',
    age: 25
  },
  header: {
    'Content-Type': 'application/json'
  },
  success: (res) => {
    console.log('Submit successful', res.data)
  }
})

Data Storage Examples

javascript
// Asynchronously store data
uni.setStorage({
  key: 'userInfo',
  data: {
    name: 'John Doe',
    age: 25
  },
  success: () => {
    console.log('Storage successful')
  }
})

// Synchronously store data
try {
  uni.setStorageSync('token', 'abc123')
  console.log('Storage successful')
} catch (e) {
  console.error('Storage failed', e)
}

// Asynchronously get data
uni.getStorage({
  key: 'userInfo',
  success: (res) => {
    console.log('Get successful', res.data)
  }
})

// Synchronously get data
try {
  const token = uni.getStorageSync('token')
  console.log('Get successful', token)
} catch (e) {
  console.error('Get failed', e)
}
javascript
// Navigate to new page
uni.navigateTo({
  url: '/pages/detail/detail?id=123'
})

// Redirect to new page
uni.redirectTo({
  url: '/pages/login/login'
})

// Go back to previous page
uni.navigateBack({
  delta: 1
})

// Jump to tabBar page
uni.switchTab({
  url: '/pages/index/index'
})

Interactive Feedback Examples

javascript
// Show toast
uni.showToast({
  title: 'Operation successful',
  icon: 'success',
  duration: 2000
})

// Show loading
uni.showLoading({
  title: 'Loading...'
})

// Hide loading
setTimeout(() => {
  uni.hideLoading()
}, 2000)

// Show modal dialog
uni.showModal({
  title: 'Prompt',
  content: 'Are you sure you want to delete this record?',
  success: (res) => {
    if (res.confirm) {
      console.log('User clicked confirm')
    } else if (res.cancel) {
      console.log('User clicked cancel')
    }
  }
})

System Information Examples

javascript
// Get system information
uni.getSystemInfo({
  success: (res) => {
    console.log('Device brand:', res.brand)
    console.log('Device model:', res.model)
    console.log('Operating system:', res.platform)
    console.log('System version:', res.system)
    console.log('Screen width:', res.screenWidth)
    console.log('Screen height:', res.screenHeight)
  }
})

// Synchronously get system information
try {
  const res = uni.getSystemInfoSync()
  console.log('System information:', res)
} catch (e) {
  console.error('Failed to get system information', e)
}

Choose Image Examples

javascript
// Choose image
uni.chooseImage({
  count: 1,
  sizeType: ['original', 'compressed'],
  sourceType: ['album', 'camera'],
  success: (res) => {
    const tempFilePaths = res.tempFilePaths
    console.log('Selected images:', tempFilePaths)
    
    // Preview image
    uni.previewImage({
      urls: tempFilePaths
    })
  }
})

API Compatibility

Different platforms may have different levels of support for APIs. Please check the compatibility notes for specific APIs before use:

API CategoryH5Mini ProgramApp
Network Requests
Data Storage
Interface Interaction
Route Navigation
Device InformationPartial
Media FunctionsPartial
Location ServicesPartial
File OperationsPartial
Third-party PlatformPartial

Important Notes

  1. Asynchronous APIs: Most APIs are asynchronous and need to handle results through success, fail, and complete callback functions
  2. Synchronous APIs: Synchronous APIs usually end with Sync and will block the current thread, use with caution
  3. Platform Differences: Different platforms may have different support for APIs, pay attention to compatibility during development
  4. Permission Requests: Some APIs require user authorization before use, such as location, camera, microphone, etc.
  5. Error Handling: It's recommended to add error handling logic for each API call
  • Getting Started - Learn how to create and run uni-app projects
  • Network Requests - Detailed guide on using network requests
  • Data Storage - Learn best practices for local data storage
  • FAQ - View common questions and solutions for API usage

Last Updated:

一次开发,多端部署 - 让跨平台开发更简单