【微信小程序】第六章 总结

目录

6.1 网络API

6.1.1 发起网络请求

6.1.2 上传文件

6.1.3 下载文件

6.2 多媒体API

6.2.1 图片API

1.选择图片或拍照

2.预览图片

3.获取图片信息

4.保存图片到系统相册

6.2.2 录音API

1.开始录音

2.停止录音

6.2.3 音频播放控制API

1.播放语音

2.暂停播放

3.结束播放

6.2.4 音乐播放控制API

1.播放音乐

2.获取音乐播放状态

3. 控制音乐播放进度

4.暂停播放音乐

5.停止播放音乐

6.监听音乐播放

7.监听音乐暂停

8.监听音乐停止

9.案例展示

6.3 文件API 

1.保存文件

2.获取本地文件列表

3.获取本地文件的文件信息

4.删除本地文件

5.打开文档

6.4 本地数据及缓存API 

6.4.1 保存数据

1.wx.setStorage(Object)

2.wx.setStorageSync(key,data)

6.4.2 获取数据

1.wx.getStorage(Object)

2.wx.getStorageSync(key) 

6.4.3 删除数据

1.wx.removeStorage(Object)

2.wx.removeStorageSync(key)

6.4.4 清空数据

1.wx.clearStorage()

2.wx.clearStorageSync()

6.5 位置信息API 

6.5.1 获取位置信息

6.5.2 选择位置信息

6.5.3 显示位置信息

6.6 设备相关API

6.6.1 获取系统信息

6.6.2 网络状态

1.获取网络状态

2.监听网络状态变化

6.6.3 拨打电话

6.6.4 扫描二维码


6.1 网络API

微信小程序处理的数据通常从后台服务器获取, 再将处理过的结果保存到后台服务器,这就要求微信小程序要有与后台进行交互的能力。 微信原生API接口或第三方API提供了各类接口实现前后端交互。

网络API可以帮助开发者实现网络URL访问调用、文件的上传和下载、网络套接字的使用等功能处理。 微信开发团队提供了10 个网络API接口。

■ wx.request(Object) 接口 用于发起HTTPS请求。

■ wx.uploadFile(Object)接口 用于将本地资源上传到后台服务器。

■ wx.downloadFile(Object)接口 用于下载文件资源到本地。

■ wx.connectSocket(Object)接口 用于创建一个 WebSocket 连接。

■ wx.sendSocketMessage(Object)接口 用于实现通过 WebSocket 连接发送数据。

■ wx.closeSocket(Object) 接口 用于关闭 WebSocket 连接。

■ wx.onSocketOpen(Object)接口 用于监听 WebSocket 连接打开事件。

■ wx.onSocketError(CallBack) 接口用于监听 WebSocket 错误。

■ wx.onSocketMessage(CallBack) 接口 用于实现监听 WebSocket 接收到服务器的消息事件。

■ wx.onSocketClose(CallBack) 接口 用于实现监听 WebSocket 关闭。 

6.1.1 发起网络请求

wx.request(Object) 实现向服务器发送请求、获取数据等各种网络交互操作, 其相关参数如表所示。一个微信小程序同时只能有5 个网络请求连接, 并且是HTTPS请求。

示例代码:

Page({
  data:{
    html:''
  },
  getbaidutap:function(){
    var that=this;
    wx.request({
      url: 'https://www.baidu.com/',
      data:{},
      header:{'Content-Type':'application/json'},
      success:function(res){
        console.log(res);
        that.setData({
          html:res.data
        })
      }
    })
  }
})
<button type="primary" bind:tap="getbaidutap">获取HTML数据</button>
<textarea value="{{html}}" auto-height maxlength="0"/>

运行效果:

例如,通过wx.request(Object)的GET方法获取邮政编码对应的地址信息。

示例代码:

<view>邮政编码:</view>
<input type="text" bindinput="input" placeholder="6位邮政编码"/>
<button type="primary" bind:tap="find">查询</button>
<block wx:for="{{address}}">
  <block wx:for="{{item}}">
    <text>{{item}}</text>
  </block>
</block>
Page({
  data:{
    postcode:'',
    address:[],
    errMsg:'',
    error_code:-1
  },
  input:function(e){
    this.setData({
      postcode:e.detail.value,
    })
    console.log(e.detail.value)
  },
  find:function(){
    var postcode=this.data.postcode;
    if(postcode!=null&&postcode!=''){
      var self=this;
      wx.showToast({
        title: '正在查询,请稍后....',
        icon:'loading',
        duration:10000
      });
      wx.request({
        url: 'https://v.juhe.cn/postcode/query',
        data:{
          'postcode':postcode,
          'key':'0ff9bfccdf147476e067de994eb5496e'
        },
        header:{
          'Content-Type':'application/json',
        },
        method:'GET',
        success:function(res){
          wx.hideToast();
          if (res.data.error_code==0) {
            console.log(res);
            self.setData({
              errMsg:'',
              error_code:res.data.error_code,
              address:res.data.result.list
            })
          }else{
            self.setData({
              errMsg:res.data.reason||res.data.reason,
              error_code:res.data.error_code
            })
          }
        }
      })
    }
  }
})

运行效果:

例如,通过wx.request(Object)的POST方法获取邮政编码对应的地址信息。

示例代码:

Page({
  data:{
    postcode:'',
    address:[],
    errMsg:'',
    error_code:-1
  },
  input:function(e){
    this.setData({
      postcode:e.detail.value,
    })
    console.log(e.detail.value)
  },
  find:function(){
    var postcode=this.data.postcode;
    if(postcode!=null&&postcode!=''){
      var self=this;
      wx.showToast({
        title: '正在查询,请稍后....',
        icon:'loading',
        duration:10000
      });
      wx.request({
        url: 'https://v.juhe.cn/postcode/query',
        data:{
          'postcode':postcode,
          'key':'0ff9bfccdf147476e067de994eb5496e'
        },
        header:{
          'Content-Type':'application/x-www-form-urlencoded',
        },
        method:'POST',
        success:function(res){
          wx.hideToast();
          if (res.data.error_code==0) {
            console.log(res);
            self.setData({
              errMsg:'',
              error_code:res.data.error_code,
              address:res.data.result.list
            })
          }else{
            self.setData({
              errMsg:res.data.reason||res.data.reason,
              error_code:res.data.error_code
            })
          }
        }
      })
    }
  }
})
<view>邮政编码:</view>
<input type="text" bindinput="input" placeholder="6位邮政编码"/>
<button type="primary" bind:tap="find">查询</button>
<block wx:for="{{address}}">
  <block wx:for="{{item}}">
    <text>{{item}}</text>
  </block>
</block>

运行效果:

6.1.2 上传文件

wx.uploadFile(Object) 接口用于将本地资源上传到开发者服务器, 并在客户端发起一个HTTPSPOST 请求, 其相关参数如表所示。

通过 wx.uploadFile(Object) , 可以将图片上传到服务器并显示。

示例代码:
 

Page({
  data: {
    imag: null,
  },
  uploadimage: function() {
    var that = this;
    wx.chooseImage({
      success: function(res) {
        var tempFilePath = res.tempFilePaths;
        upload(that, tempFilePath);
      }
    });

    function upload(page, path) {
      wx.showLoading({
        title: '正在上传',
        mask: true
      });
      
      wx.uploadFile({
        filePath: path[0],
        name: 'file',
        url: '', // 替换为你的上传地址
        success: function(res) {
          console.log(res);
          if (res.statusCode !== 200) {
            wx.showModal({
              title: '提示',
              content: '上传失败',
              showCancel: false
            });
            return;
          }
          var data = res.data;
          page.setData({
            imag: path[0]
          });
        },
        fail: function(e) {
          console.log(e);
          wx.showModal({
            title: '提示',
            content: '上传失败',
            showCancel: false
          });
        },
        complete: function() {
          wx.hideLoading();
        }
      });
    }
  }
});
<button type="primary" bind:tap="uploadimage">上传图片</button>
<image src="{{imag}}" mode="widthFix"/>

运行效果:

6.1.3 下载文件

wx. downloadFile(Object)接口用于实现从开发者服务器下载文件资源到本地, 在客户端直接发起一个 HTTPGET 请求, 返回文件的本地临时路径。 其相关参数如表所示。

例如,通过wx. downloadFile(Object)实现从服务器中下载图片,后台服务采用WAMP软件在本机搭建。

示例代码:

Page({
  data:{
    img:null,
  },
  downloadimage:function(){
    var that = this;
    wx.downloadFile({
      url: "http://localhost/1.jpg", //通过WAMP软件实现
      success:function(res){
        console.log(res)
        that.setData({
          img:res.tempFilePath
        })
      }
    })
  }
 })
<button type="primary" bind:tap="downloadimage">下载图片</button>
<image src="{{img}}" mode="widthFix" style="width: 100%;height: 500px;"/>

运行效果:

6.2 多媒体API

多媒体API 主要包括图片API、录音API、音频播放控制API、音乐播放控制API 等, 其目的是丰富小程序的页面功能。

6.2.1 图片API

图片API 实现对相机拍照图片或本地相册图片进行处理, 主要包括以下4个API 接口:

■ wx.chooseImage(Object) 接口用于从本地相册选择图片或使用相机拍照。

■ wx.previewImage(Object) 接口用于预览图片。

■ wx.getImageInfo(Object) 接口用于获取图片信息。

■ wx.saveImageToPhotosAlbum(Object) 接口用于保存图片到系统相册。

1.选择图片或拍照

wx.chooseImage(Object) 接口用于从本地相册选择图片或使用相机拍照。 拍照时产生的临时路径在小程序本次启动期间可以正常使用, 若要持久保存, 则需要调用 wx.saveFile 保存图片到本地。 其相关参数如表所示。

若调用成功, 则返回 tempFilePaths 和 tempFiles , tempFilePaths 表示图片在本地临时文件路径列表。 tempFiles 表示图片的本地文件列表, 包括 path 和 size 。

示例代码:

wx.chooseImage({
  count:2,
  sizeType:['original','compressed'],
  sourceType:['album','camera'],
  success:function(res){
    var tempFilePaths=res.tempFilePaths
    var tempFiles=res.tempFiles
    console.log(tempFilePaths)
    console.log(tempFiles)
  }
})

运行效果:

2.预览图片

wx.previewImage(Object)接口主要用于预览图片, 其相关参数如表所示。

示例代码:

wx.previewImage({
  current:"http://bmob-cdn-16488.b0.upaiyun.com/2018/02/05/2.png",
  urls:["http://bmob-cdn-16488.b0.upaiyun.com/2018/02/05/1.png",
 "http://bmob-cdn-16488.b0.upaiyun.com/2018/02/05/2.png",
 "http://bmob-cdn-16488.b0.upaiyun.com/2018/02/05/3.jpg"]
 })

 运行效果:

3.获取图片信息

wx.getImageInfo(Object)接口用于获取图片信息, 其相关参数如表所示。

示例代码:

wx.chooseImage({
  success:function(res){
    wx.getImageInfo({
      src: res.tempFilePaths[0],
      success:function(e){
        console.log(e.width)
        console.log(e.height)
      }
    })
  },
})

 运行效果:

4.保存图片到系统相册

wx.saveImageToPhotosAlbum(Object)接口用于保存图片到系统相册, 需要得到用户授权scope.writePhotosAlbum。 其相关参数如表所示。

示例代码:

wx.chooseImage({
  success:function(res){
    wx.saveImageToPhotosAlbum({
      filePath: res.tempFilePaths[0],
      success:function(e){
        console.log(e)
      }
    })
  }
})

 运行效果:

6.2.2 录音API

录音API 提供了语音录制的功能, 主要包括以下两个API 接口:

■ wx.startRecord(Object) 接口用于实现开始录音。

■ wx.stopRecord(Object) 接口用于实现主动调用停止录音。

1.开始录音

wx.startRecord(Object) 接口用于实现开始录音。 当主动调用 wx.stopRecord(Object) 接口或者录音超过1 分钟时, 系统自动结束录音, 并返回录音文件的临时文件路径。 若要持久保存, 则需要调用wx.saveFile()接口。 其相关参数如表所示。

2.停止录音

wx.stopRecord(Object) 接口用于实现主动调用停止录音。

示例代码:

wx.startRecord({
  success:function(res){
    var tempFilePath=tempFilePath
  },
  fail:function(res){
  }
})
setTimeout(function(){
  wx.stopRecord()},10000)

运行效果:

6.2.3 音频播放控制API

音频播放控制API 主要用于对语音媒体文件的控制, 包括播放、暂停、停止及audio 组件的控制, 主要包括以下3 个API:

■ wx.playVoice(Object) 接口用于实现开始播放语音。

■ wx.pauseVoice(Object) 接口用于实现暂停正在播放的语音。

■ wx.stopVoice(Object) 接口用于结束播放语音。

1.播放语音

wx.playVoice(Object) 接口用于开始播放语音, 同时只允许一个语音文件播放, 如果前一个语音文件还未播放完, 则中断前一个语音文件的播放。 其相关参数如表所示。

示例代码:

wx.startRecord({
  success:function(res){
    var tempFilePath=res.tempFilePath
    wx.playVoice({
      filePath:tempFilePath,
      complete:function(){
        
      }
    })
  }
})


运行效果:

2.暂停播放

wx.pauseVoice(Object) 用于暂停正在播放的语音。再次调用 wx.playVoice(Object) 播放同一个文件时, 会从暂停处开始播放。 如果想从头开始播放, 则需要先调用 wx.stopVoice(Object) 。

示例代码:

wx.startRecord({
    success:function(res){
      var tempFilePath=res.tempFilePath
      wx.playVoice({
        filePath:tempFilePath
      })
      setTimeout(function(){
        wx.stopVoice()
      },5000)
    }
  })

运行效果:

3.结束播放

wx.stopVoice(Object) 用于结束播放语音。

示例代码:

wx.startRecord({
    success:function(res){
      var tempFilePath=res.tempFilePath
      wx.playVoice({
        filePath:tempFilePath
      })
      setTimeout(function(){
        wx.stopVoice()
      },5000)
    }
  })

运行效果:

6.2.4 音乐播放控制API

音乐播放控制API 主要用于实现对背景音乐的控制, 音乐文件只能是网络流媒体, 不能是本地音乐文件。 音乐播放控制API 主要包括以下8 个API:

■ wx.playBackgroundAudio(Object) 接口 用于播放音乐。

■ wx.getBackgroundAudioPlayerState(Object) 接口 用于获取音乐播放状态。

■ wx.seekBackgroundAudio(Object) 接口 用于定位音乐播放进度。

■ wx.pauseBackgroundAudio() 接口 用于实现暂停播放音乐。

■ wx.stopBackgroundAudio() 接口 用于实现停止播放音乐。

■ wx.onBackgroundAudioPlay(CallBack) 接口 用于实现监听音乐播放。

■ wx.onBackgroundAudioPause(CallBack) 接口 用于实现监听音乐暂停。

■ wx.onBackgroundAudioStop(CallBack) 接口 用于实现监听音乐停止。

1.播放音乐

wx.playBackgroundAudio(Object) 用于播放音乐, 同一时间只能有一首音乐处于播放状态, 其相关参数如表所示。

示例代码:

wx.playBackgroundAudio({
  dataUrl: 'http://bmob-cdn-16488.b0.upaiyun.com/2018/02/09/117e4a1b405195b18061299e2de89597.mp3',
  title:'有一天',
  coverImgUrl:'http:///bmob-cdn-16488.b0.upaiyun.com/2018/02/09/f604297140c9681880cc3d3e581f7724.jpg',
  success:function(res){
    console.log(res)//成功返回playBackgroundAudio:ok
  }
})
2.获取音乐播放状态

wx.getBackgroundAudioPlayerState(Object) 接口用于获取音乐播放状态, 其相关参数如表 所示。

接口调用成功后返回的参数如表所示。

示例代码:

wx.getBackgroundAudioPlayerState({
  success:function(res){
    var status=res.status
    var dataUrl=res.dataUrl
    var currentPosition=res.currentPosition
    var duration=res.duration
    var downloadPercent=res.downloadPercent
    console.log("播放状态:"+status)
    console.log("音乐文件地址:"+dataUrl)
    console.log("音乐文件当前播放位置:"+currentPosition)
    console.log("音乐文件的长度:"+duration)
    console.log("音乐文件的下载进度:"+downloadPercent)
  }
})
3. 控制音乐播放进度

wx.seekBackgroundAudio(Object) 接口用于控制音乐播放进度, 其相关参数如表所示。

示例代码:

wx.seekBackgroundAudio({
  position: 30,
})
4.暂停播放音乐

wx.pauseBackgroundAudio() 接口用于暂停播放音乐。

示例代码:
 

wx.playBackgroundAudio({
  dataUrl: '/music/a.mp3',
  title:'我的音乐',
  coverImgUrl:'images/poster.jpg',
  success:function(){
    console.log('开始播放音乐了');
  }
});
setTimeout(function(){
  console.log('暂停播放');
  wx.pauseBackgroundAudio();
},5000);//5秒后自动暂停
5.停止播放音乐

wx.stopBackgroundAudio() 接口用于停止播放音乐。

示例代码:

wx.playBackgroundAudio({
  dataUrl: '/music/a.mp3',
  title:'我的音乐',
  coverImgUrl:'images/poster.jpg',
  success:function(){
    console.log('开始播放音乐了');
  }
});
setTimeout(function(){
  console.log('暂停播放');
  wx.stopBackgroundAudio();
},5000);//5秒后自动停止
6.监听音乐播放

wx.onBackgroundAudioPlay(CallBack)接口用于实现监听音乐播放, 通常被wx.playBackgroundAudio(Object)方法触发, 在 CallBack 中可改变播放图标。

示例代码:

wx.playBackgroundAudio({
  dataUrl: this.data.musicData.dataUrl,
  title:this.data.musicData.title,
  coverImgUrl:this.data.musicData.coverImgUrl,
  success:function(){
    wx.onBackgroundAudioStop(function(){
      that.setData({
        isplayingMusic:false
      })
    })
  }
})
7.监听音乐暂停

wx.onBackgroundAudioPause(CallBack)接口用于实现监听音乐暂停, 通常被wx.pauseBackgroundAudio()方法触发。 在CallBack中可以改变播放图标。

8.监听音乐停止

wx.onBackgroundAudioStop(CallBack) 接口用于实现监听音乐停止, 通常被音乐自然播放停止或wx.seekBackgroundAudio(Object) 方法导致播放位置等于音乐总时长时触发。 在CallBack中可以改变播放图标。

9.案例展示

在此,以小程序 music 为案例来展示音乐API的使用。该小程序的4个页面分别为 music.wxml、music.wxss、music.json、music.js。

示例代码:
music.wxml

<view class="container">
<image class="bgaudio" src="{{changedImg? music.coverImg:'/images/hhxd.png'}}"/>
<view class="control-view">
<image src="/images/fuwu.png" bind:tap="onPositionTap" data-how="0"/>
<image src="/images/{{isPlaying? 'pause':'biouqin'}}.png" bind:tap="onAudioTap" />
<image src="/images/kabou.png" bind:tap="onStopTap"/>
<image src="/images/shoucang.png" bind:tap="onPositionTap" data-how="1"/>
</view>
</view>

图片资源请自行修改。

music.wxss

.bgaudio{
  height: 350px;
  width: 350px;
  margin-bottom: 100rpx;
}
.control-view image{
  height: 64rpx;
  width: 64rpx;
  margin: 30rpx;
}

music.json

{
  "usingComponents": {
  }
}

music.js

Page({
  data:{
    isPlaying:false,
    coverImg:false,
    changedImg:false,
    music:{
      "url":"http://bmob-cdn-16488.b0.upaiyun.com/2018/02/09/117e4a1b405195b8061299e289597.mp3",
      "title":"盛晓玫 -有一天",
      "coverImg":"http://bmob-cdn-16488.b0.upaiyun.com/2018/02/09/f604297140c9681880cc3d3e581f7724.jpg"
    },
  },
  onLoad:function(){
    this.onAudioState();
  },
  onAudioTap:function(event){
    if (this.data.isPlaying) {
      wx.pauseBackgroundAudio();
    }else{
      let music=this.data.music;
      wx.playBackgroundAudio({
        dataUrl: music.url,
        title:music.title,
        coverImgUrl:music.coverImg
      })
    }
  },
  onStopTap:function(){
    let that=this;
    wx.stopBackgroundAudio({
      success:function(){
        that.setData({
          isPlaying:false,changedImg:false
        });
      }
    })
  },
  onPositionTap:function(event){
    let how=event.target.dataset.how;
    wx.getBackgroundAudioPlayerState({
      success:function(res){
        let status=res.status;
        if (status===1) {
          let duration=res.duration;
          let currentPosition=res.currentPosition;
          if (how==="0") {
            let position=currentPosition-10;
            if (position<0) {
              position=1;
            }
            wx.seekBackgroundAudio({
              position: position
            });
            wx.showToast({
              title: '快退10s',
              duration:500
            });
          }
          if (how==="1") {
            let position=currentPosition+10;
            if (position>duration) {
              position=duration-1;
            }
            wx.seekBackgroundAudio({
              position: position,
            });
            wx.showToast({
              title: '快进10s',
              duration:500
            })
          }
        }else{
            wx.showToast({
              title: '音乐未播放',
              duration:800
            })
          }
      }
    })
  },
  onAudioState:function(){
    let that=this;
    wx.onBackgroundAudioPause(function() {
      that.setData({
        isPlaying:true,
        changedImg:true
      });
      console.log("on Play");
    })
    wx.onBackgroundAudioPause(function() {
      that.setData({
        isPlaying:false
      });
      console.log("on Pause")
    });
    wx.onBackgroundAudioStop(function() {
      that.setData({
        isPlaying:false,
        changedImg:false
      })
      console.log("on stop");
    })
  }
})

运行效果(无图片资源,其他图片代替):

6.3 文件API 

从网络上下载或录音的文件都是临时保存的, 若要持久保存, 需要用到文件API。 文件API 提供了打开、保存、删除等操作本地文件的能力, 主要包括以下5 个API 接口:

■ wx.saveFile(Object) 接口 用于保存文件到本地。

■ wx.getSaveFileList(Object) 接口 用于获取本地已保存的文件列表。

■ wx.getSaveFileInfo(Object) 接口 用于获取本地文件的文件信息。

■ wx.removeSaveFile(Object) 接口 用于删除本地存储的文件。

■ wx.openDocument(Object) 接口 用于新开页面打开文档, 支持格式: doc、xls、ppt、pdf、docx、xlsx、ppts。

1.保存文件

wx.saveFile(Object) 用于保存文件到本地, 其相关参数如表所示。

示例代码:

wx.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success: function(res) {
      var tempFilePaths = res.tempFilePaths[0];
      wx.saveFile({
        tempFilePath: tempFilePaths,
        success: function(res) {
          var saveFilePath = res.saveFilePath;
          console.log(saveFilePath);
        }
      });
    }
  });

运行效果:

2.获取本地文件列表

wx.getSaveFileList(Object) 接口用于获取本地已保存的文件列表, 如果调用成功, 则返回文件的本地路径、文件大小和文件保存时的时间戳(从1970/01/01 08: 00: 00 到当前时间的秒数) 文件列表。 其相关参数如表所示。

示例代码:

  wx.getSavedFileList({
    success: function(res) {
      console.log("文件列表:", res.fileList);
    }
  });

运行效果:

3.获取本地文件的文件信息

wx.getSaveFileInfo(Object) 接口用于获取本地文件的文件信息, 此接口只能用于获取已保存到本地的文件, 若需要获取临时文件信息, 则使用 wx.getFileInfo(Object) 接口。 其相关参数如表所示。

示例代码:

wx.chooseImage({
    count:1,
    sizeType:['original','compressed'],
    sourceType:['album','camera'],
    success:function(res){
      var tempFilePaths = res.tempFilePaths[0]
      wx.saveFile({
        tempFilePath:tempFilePaths,
        success:function(res){
          var saveFilePath = res.saveFilePath;
          wx.getSavedFileInfo({
            filePath:saveFilePath,
            success:function(res){
              console.log(res.size)
            }
          })
        }
      })
    }
  })

运行效果:

4.删除本地文件

wx.removeSaveFile(Object) 接口用于删除本地存储的文件, 其相关参数如表所示。

示例代码:

//js
wx.getSavedFileList({
  success:function(res){
    if(res.fileList.Length > 0 ){
      wx.removeSavedFile({
        filePath:res.fileList[0].filePath,
        complete:function(res){
          console.log(res)
        }
      })
    }
  }
})

运行效果:

5.打开文档

wx.openDocument(Object) 接口用于新开页面打开文档, 支持格式有doc、xls、ppt、pdf、docx、xlsx、pptx, 其相关参数如表所示。

示例代码:
 

wx.downloadFile({
  url: "http://localhost/fm2.pdf",
  success:function(res){
    var tempFilePath = res.tempFilePath;
    wx.openDocument({
      filePath: tempFilePath,
      success:function(res){
        console.log("打开成功")
      }
    })
  }
})

运行效果:

6.4 本地数据及缓存API 

小程序提供了以键值对的形式进行本地数据缓存功能,并且是永久存储的,但最大不超过10MB,其目的是提高加载速度。数据缓存的接口主要有4个:

■ wx.setStorage(Object) 或 wx.setStorageSync(key,data) 接口 用于设置缓存数据。

■ wx.getStorage(Object) 或 wx.getStorageSync(key) 接口 用于获取缓存数据。

■ wx.removeStorage(Object) 或 wx.removeStorageSync(key) 接口 用于删除指定缓存数据。

■ wx.clearStorage() 或 wx.clearStorageSync() 接口 用于清除缓存数据。

其中, 带Sync后缀的为同步接口, 不带Sync后缀的为异步接口。

6.4.1 保存数据

1.wx.setStorage(Object)

wx.setStorage(Object) 接口将数据存储到本地缓存接口指定的key中, 接口执行后会覆盖原来key对应的内容。 其参数如表所示。

示例代码:

wx.setStorage({
  key:'name',
  data:'sdy',
  success:function(res){
    console.log(res)
  }
})

运行效果:

2.wx.setStorageSync(key,data)

wx.setStorageSync(key,data) 是同步接口, 其参数只有keydata

wx.setStorageSync('age','25')

6.4.2 获取数据

1.wx.getStorage(Object)

wx.getStorage(Object) 接口是从本地缓存中异步获取指定key对应的内容。 其相关参数如表所示。

示例代码:

wx.getStorage({
  key:'name',
  success:function(res){
    console.log(res.data)
  },
})

 运行效果:

2.wx.getStorageSync(key) 

wx.getStorageSync(key)  从本地缓存中同步获取指定key对应的内容。 其参数只有key。

示例代码:

try{
  var value=wx.getStorageSync('age')
  if(value){
    console.log("获取成功"+value)
  }
}catch(e){
  console.log("获取失败")
}

运行效果:

6.4.3 删除数据

1.wx.removeStorage(Object)

wx.removeStorage(Object) 接口用于从本地缓存中异步移除指定key。 其相关参数如表所示。

示例代码:

wx.removeStorage({
  key: 'name',
  success:function(res){
    console.log("删除成功")
  },
  fail:function(){
    console.log("删除失败")
  }
})

 运行效果:

2.wx.removeStorageSync(key)

wx.removeStorageSync(key) 接口用于从本地缓存中同步删除指定key对应的内容。 其参数只有key

示例代码:

try{
  wx.removeStorageSync('name')
}catch(e){
  //Do something when catch error
}

6.4.4 清空数据

1.wx.clearStorage()

wx.clearStorage() 接口用于异步清理本地数据缓存, 没有参数。

示例代码:
 

wx.getStorage({
  key:'name',
  success:function(res){
    wx.clearStorage(); // 清理本地数据缓存
  },
});

运行效果:

2.wx.clearStorageSync()

wx.clearStorageSync() 接口用于同步清理本地数据缓存。

示例代码:

try{
  wx.clearStorageSync()
}catch(e){
  
}

6.5 位置信息API 

小程序可以通过位置信息API来获取或显示本地位置信息, 小程序支持WGS84和GCj02标准, WGS84标准为地球坐标系, 是国际上通用的坐标系;GCj02标准是中国国家测绘局制定的地理信息系统的坐标系统, 是由WGS84坐标系经加密后的坐标系, 又称为火星坐标系。 默认为WGS84标准, 若要查看位置需要使用GCj02标准。 主要包括以下3 个API接口:

■ wx.getLocation(Object) 接口 用于获取位置信息。

■ wx.chooseLocation(Object) 接口 用于选择位置信息。

■ wx.openLocation(Object) 接口 用于通过地图显示位置。

6.5.1 获取位置信息

wx.getLocation(Object) 接口用于获取当前用户的地理位置、速度, 需要用户开启定位功能, 当用户离开小程序后, 无法获取当前的地理位置及速度, 当用户点击“显示在聊天顶部” 时, 可以获取到定位信息, 其相关参数如表所示。

wx.getLocation(Object) 调用成功后, 返回的参数如表所示。

示例代码:

wx.getLocation({
  type:'wgs84',
  success:function(res){
    console.log("经度:"+res.longitude);
    console.log("纬度:"+res.latitude);
    console.log("速度:"+res.longitude);
    console.log("位置的精确度:"+res.accuracy);
    console.log("水平精确度:"+res.horizontalAccuracy);
    console.log("垂直精确度:"+res.verticalAccuracy);
  },
})

 运行效果:

6.5.2 选择位置信息

wx.chooseLocation(Object) 接口用于在打开的地图中选择位置, 用户选择位置后可返回当前位置的名称、地址、经纬度信息。 其相关参数如表所示。

wx.chooseLocation(Object) 调用成功后, 返回的参数如表所示。

示例代码:

wx.chooseLocation({
  success:function(res){
    console.log("位置的名称:"+res.name)
    console.log("位置的地址:"+res.address)
    console.log("位置的经度:"+res.longitude)
    console.log("位置的纬度:"+res.latitude)
  }
})

运行效果:

6.5.3 显示位置信息

wx.openLocation(Object)接口用于在微信内置地图中显示位置信息, 其相关参数如表所示。

示例代码:

6.6 设备相关API

设备相关的接口用于获取设备相关信息, 主要包括系统信息、网络状态、拨打电话及扫码等。 主要包括以下5 个接口API:

■ wx.getSystemInfo(Object) 接口、wx.getSystemInfoSync() 接口 用于获取系统信息。

■ wx.getNetworkType(Object) 接口 用于获取网络类型。

■ wx.onNetworkStatusChange(CallBack) 接口 用于监测网络状态改变。

■ wx.makePhoneCall(Object) 接口 用于拨打电话。

■ wx.scanCode(Object) 接口 用于扫描二维码。

6.6.1 获取系统信息

wx.getSystemInfo(Object) 接口、wx.getSystemInfoSync() 接口分别用于异步和同步获取系统信息。 其相关参数如表所示。

wx.getSystemInfo() 接口或 wx.getSystemInfoSync() 接口调用成功后, 返回系统相关信息, 如表所示。

示例代码:

wx.getSystemInfo({
  success:function(res){
    console.log("手机型号" + res.model);
    console.log("设备像素比" + res.pixelRatio);
    console.log("窗口的宽度" + res.windowWidth);
    console.log("窗口的高度" + res.windowHeight);
    console.log("微信的版本号" + res.version);
    console.log("操作系统版本" + res.system);
    console.log("客户端平台" + res.platform);
  },
})

运行效果:

6.6.2 网络状态

1.获取网络状态

wx.getNetWorkType(Object) 用于获取网络类型, 其相关参数如表所示。

如果 wx.getNetWorkType() 接口被成功调用, 则返回网络类型包, 有wifi2G3G4Gunknown(Android下不常见的网络类型)、none(无网络)。

示例代码:

wx.getNetworkType({
  success:function(res){
    console.log(res.networkType)
  },
})

运行效果:

2.监听网络状态变化

wx.onNetworkStatusChange(CallBack) 接口用于监听网络状态变化, 当网络状态变化时,返回当前网络状态类型及是否有网络连接。

示例代码:
 

wx.onNetworkStatusChange(function(res){
  console.log("网络是否连接" + res.isConnected)
  console.log("变化后的网络类型" + res.networkType)
})

运行效果:

6.6.3 拨打电话

wx.makePhoneCall(Object) 接口用于实现调用手机拨打电话, 其相关参数如表所示。

示例代码:

wx.makePhoneCall({
  phoneNumber: '14796770916',
})

 运行效果:

6.6.4 扫描二维码

wx.scanCode(Object) 接口用于调起客户端扫码界面, 扫码成功后返回相应的内容, 其相关参数如表所示。

扫码成功后, 返回的数据如表所示。

示例代码:

wx.scanCode({
  success:(res) => {
    console.log(res.result)
    console.log(res.scanType)
    console.log(res.charSet)
    console.log(res.path)
  }
})
wx.scanCode({
  onlyFromCamera:true,
  success:(res) => {
    console.log(res)
  }
})

运行效果:

  • 11
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值