第六章总结

6.1  网络API

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

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

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

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

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

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

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

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

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

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

6.1.1 发送网络请求

wx.request(Object) 实现向服务器发送请求、获取数据等各种网络交互操作

通过wx.request(Object) 获取百度(https://www.baidu.com)首页的数据

示例代码:

//baidu.wxml
<button type="primary"bindtap="getbaidutap">获取HTML数据</button>
<textarea value='{{html}}'auto-heightmaxlength='0'> </textarea>
//baidu.js
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
          })
        }
      })
    }
  })

运行效果:

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

示例代码:

//postcode.wxml
<view>邮政编码:</view>
<input type="text"bindinput="input"placeholder='6位邮政编码'/>
<button type="primary"bindtap="find">查询</button>
<block wx:for="{{address}}">
<block wx:for="{{item}}">
<text>{{item}}</text>
</block>
</block>

//postcode.js
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;
    //显示toast提示消息
    wx.showToast({
      title:'正在查询,请稍候.....',
      icon:'loading',
      duration:10000
    });
 wx.request({
   url:'https://v.juhe.cn/postcode/query',//第三方后台服务器
   data:{
     'postcode':postcode,
     'key':'off9bfcccdf147476e067de994eb5496e'//第三方提供
   },
   header:{
     'Content-Type':'application/json',
   },
   method:'GET',//方法为GET
   success:function(res){
     wx.hideToast();//隐藏toast
     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
       })
     }
   }
 })
  }
}
})

6.1.2 上传文件

wx.upladFile(Object)接口用于将本地资源上传到开发者服务器,并在客户端发起一个HTTPS POST请求

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

示例代码:

.js

Page({
  data: {
   img:null,
  },
  uploadimage:function(){
    var that=this;
    wx.chooseImage({
      success:function(res){
        var tempFilePaths=res.tempFilePaths
        upload(this.tempFilePaths);
      }
    })
    function upload(page,path){
      wx.showToast({
        title: '正在上传',
      }),
      wx.uploadFile({
        filePath: 'path[0]',
        name: 'file',
        url: "http://localhost/",
        success:function(res){
          console.log(res);
          if(res.statusCode!=200){
            wx.showModal({
              title: '提示',
              content: '上传失败',
              showCancel:false
            })
            return;
          }
        var data=res.data
        page.setData({
  img:path[0]
})
      },
      fail:function(e){
        console.log(e);
        wx.showModal({
          title: '提示',
          content: '上传失败',
         showCancel:false
        })
      },
      complete:function(){
        wx.hideToast();
      }
      })
    }
  }
})

.wxml

<button type="primary" bindtap="uploadimage">上传图片</button>
<image src="{{img}}" mode="widthFix"/>

6.1.3 下载文件

wx.upladFile(Object)接口用于实现从开发者服务器下载文件资源到本地,在客户端直接发起一个HTTP GET请求,返回文件的本地临时路径

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

6.2  多媒体API

6.2.1 图片API

  • wx.chooseImage(Object) 接口  用于从本地相册选择图片或使用相机拍照
  • wx.previewImage(Object) 接口  用于预览图片
  • wx.getImageInfo(Object) 接口  用于获取图片信息
  • wx.saveImageToPhotosAIbum(Object) 接口  用于保存图片到系统相册

1.选择图片或拍照

若调用成功,则返回tempFilePaths 和tempFile,tempFilePaths表示图片在本地临时文件路径列表,tempFile表示图片的本地文件列表

示例代码:

wx.chooseImage({
  count:2,//默认值为9
  sizeType:['original','compressed'],//可以指定是原图还是压缩图,默认二者都有
  sourceType:['album','camera'],//可以指定来源是相册还是相机,默认二者都有
  success:function(res){
    //返回选定照片的本地文件路径列表,tempFilePath 可以作为img标签的src属性来显示图片
    var tempFilePaths=res.tempFilePaths
    var tempFiles=res.tempFilePaths;
    console.log(tempFilePaths)
    console.log(tempFiles)
  }
})

2.预览图片

示例代码:

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.chooseImage({
  success:function(res){
    wx.getImageInfo({
      src: res.tempFilePaths[0],
      success:function(e){
        console.log(e.width)
        console.log(e.height)
      }
    })
  },
})

4.保存图片到系统相册

示例代码:

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

6.2.2  录音API

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

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

1.开始录音

2.停止录音

示例代码:

wx.startRecord)
({
  success:function(res){
    var tempFilePath=res.tempFilePath
  },
  fail:function(res){
    //录音失败
  }
})
setTimeout(function){
  //结束录音
  wx.stopRecord()
},10000)

6.2.3  音频播放控制API

  • wx.playVoice(Objece)  接口  用于实现开始播放语音
  • wx.pauseVoice(Objece)  接口  用于实现暂停正在播放的语音
  • wx.stopVoice(Objece)  接口  用于结束播放语音

1.播放语音

示例代码:

wx.startRecord({
  success:function(res){
    var tempFilePath=res.tempFilePath
    wx.playVoice({  //录音完后立即播放
      filePath: tempFilePath,
      complete:function(){
      }
    })
  }
})

2.暂停播放

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

     setTimeout(function(){
       //暂停播放
       wx.pauseVoice()
     },5000)
    }
    })

3.结束播放

示例代码:

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

     setTimeout(function(){
       wx.stopVoice()
     },5000)
    }
    })

6.2.4  音乐播放控制API

  • wx.playBackgroundAudio(Object) 接口  用于播放音乐
  • wx.getBackgroundAudioPlayerState(Object) 接口  用于获取音乐播放状态
  • wx.seekBackgroundAudio(Object) 接口  用于定位音乐播放进度
  • wx.pauseBackgroundAudio(Object) 接口  用于实现暂停播放音乐
  • wx.stopBackgroundAudio(Object) 接口  用于实现停止播放音乐
  • wx.onBackgroundAudioPlay(Object) 接口  用于实现监听音乐播放
  • wx.onBackgroundAudioPause(Object) 接口  用于实现监听音乐暂停
  • wx.onBackgroundAudioStop(Object) 接口  用于实现监听音乐停止

1.播放音乐

示例代码:

wx.playBackgroundAudio({
  dataUrl: 'http://bmob-cdn-16488.b0.upaiyun.com/2018/02/09/117e4alb405195b18061299e2de89597.mp3',
  title:'有一天',
  coverImgUrl:'http://bmob-cdn-16488.b0.upaiyun.com/2018/02/09/f604297140c9681990cc3d3e581f7724.jpg',
  success:function(res){
    console.log(res)//成功返回playBackgroundAudio:ok
  }
})

2.获取音乐播放状态

示例代码:

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

3.控制音乐播放进度

示例代码:

wx.seekBackgroundAudio({
  position: 30,
})

4.暂停播放音乐

示例代码:

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

5.停止播放音乐

示例代码:

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.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)接口用于实现监听音乐暂停

8.监听音乐停止

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

9.案例展示

wxml:

<view class="container">
<image class="bgaudio"src = "{{changedImg? music.coverImg:'../image/obt.jpg'}}"/>
<view class ="control-view">
<image src="/pages/image/6.jpg" bindtap="onPositionTap"data-how= "0 "/>
<image src = "/pages/image/1.jpg" bindtap = "onAudioTap"/>
<image src ="/pages/image/2.jpg"bindtap = "onStopTap"/>
<image src ="/pages/image/3.jpg"bindtap ="onPositionTap"data-how = "1"/>
</view >
</view >

js:

Page({
  data:{
  isPlaying:false,
  coverImgchangedImg:false,	
  music:{
   "url":"../image/xtq.mp4",
  "title":"文字",
  "coverImg":
  "../image/obt.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.onBackgroundAudioPlay(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");	
});	
}
})

wxss:

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

6.3  文件API

  • wx.saveFile(Object)接口  用于保存文件到本地
  • wx.getSavedFileList(Object) 接口  用于获取本地已保存的文件列表
  • wx.getSaveFileInfo(Object) 接口  用于获取本地文件的文件信息
  • wx.removeSaveFile(Object) 接口  用于删除本地存储的文件
  • wx.openDocument(Object) 接口  用于新开页面打开文档,支持格式:doc、xls、ppt、pdf、docx、xlsx、ppts

1.保存文件

示例代码:

saveImg:function(){
  wx.chooseImage({
    count:1,//默认值为9
    sizeType:['original','compressed'],//可以指定是原图还是压缩图,默认二者都有
    sourceType:['album','camera'],//可以指定来源是相册还是相机,默认二者都有
    success:function(res){
      var tempFilePaths=res.tempFilePaths[0]
      wx.saveFile({
        tempFilePath:tempFilePaths,
        success:function(res){
          var saveFilePath=res.savedFilePath;
          console.log(saveFilePath)
        }
      })
    }
  })
}

 2.获取本地文件列表

示例代码:

wx.getSavedFileList({
  success:function(res){
    that.setData({
      fileList:res,fileList
    })
  }
})

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

示例代码:

 wx.chooseImage({
    count:1,//默认值为9
    sizeType:['original','compressed'],//可以指定是原图还是压缩图,默认二者都有
    sourceType:['album','camera'],//可以指定来源是相册还是相机,默认二者都有
    success:function(res){
      var tempFilePaths=res.tempFilePaths[0]
      wx.saveFile({
        tempFilePath:tempFilePaths,
        success:function(res){
          var saveFilePath=res.savedFilePath;
          wx.getSavedFileInfo({
            filePath:saveFilePath,
            success:function(res){
              console.log(res.size)
            }
          })
        }
      })
    }
  })

4.删除本地文件

示例代码:

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.downloadFile({
  url: 'http://localhost/fm2.pdf', //在本地通过wxamp搭建服务器
  success:function(res){
var tempFilePath=res.tempFilePath;
wx.openDocument({
  filePath: tempFilePath,
  success:function(res){
    console.log("打开成功")
  }
})
  }
})

6.4  本地数据及缓存API

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

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

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

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

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

6.4.1 保存数据

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

示例代码:

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

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

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

6.4.2 获取数据

1.wx.getStorage(Object)接口是从本地缓存中异步获取指定key对应的内容

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

2.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)接口用于从本地缓存中异步移除指定key

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

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

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

6.4.4 清空数据

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

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

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

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

6.5  位置信息API

  • wx.getLocation(Object) 接口  用于获取位置信息
  • wx.chooseLocation(Object) 接口  用于选择位置信息
  • wx.openLocation(Object) 接口  用于通过地图显示位置

6.5.1 获取位置信息

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.shooseLocation({
  success:function(res){
    console.log("位置的名称:"+res.name)
    console.log("位置的地址:"+res.address)
    console.log("位置的经度:"+res.longitude)
    console.log("位置的维度:"+res.latitude)
  }
})

6.5.3 显示位置信息

wx.getLocation({
  type:'gcj02',//返回可以用于wx.openLocation的经纬度
  success:function(res){
    var latitude=res.latitude
    var longitude=res.longitude
    wx.openLocation({
      latitude: latitude,
      longitude: longitude,
      scale:10,
      name:'智慧国际酒店',
      address:'西安市长安区西长安区300号'
    })
  }
})

6.6 设备相关API

  • wx.getSystemInfo(Object) 接口   、wx.getSystemInfoSync()  接口  用于获取系统信息
  • wx.getNetworkType(Object) 接口  用于获取网络类型
  • wx.onNetworkStausChange(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({
  success:function(res){
    console.log(res.networkType)
  },
})

2.监听网络状态变化

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

6.6.3 拨打电话

wx.makePhoneCall({
  phoneNumber: '18092585093'//需要拨打的电话号码
})

6.6.4 扫描二维码

//允许从相机和相册扫码
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)
  }
})

  • 36
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值