当前位置: 移动技术网 > 移动技术>移动开发>IOS > 【swift】 使用bmob后端云进行增删改查以及上传文件的部分代码

【swift】 使用bmob后端云进行增删改查以及上传文件的部分代码

2018年03月27日  | 移动技术网移动技术  | 我要评论

【swift】 使用bmob后端云进行增删改查以及上传文件的部分代码,bmob后端云作为国内非常不错的后端云平台,提供了丰富的后端云服务,也让开发者能够用几行代码搞定对于表的增删改查操作。

然而bmob所提供的开发文档是OC的,这对于笔者这种用swift进行开发的人造成了很大的不便。

因此笔者在这里分享一下笔者常用的bmob后端云的swift代码。

(至于如何配置bmob后端云……自行百度吧,教程写得都很好,笔者就不献丑了哈)

//添加数据(表名,列名,内容)

func insertData(className:String,key:String,content:String){

//创建表

let object = BmobObject(className: className)

//设置数据对象

object.setObject(content, forKey: key)

//存储到云

object.saveInBackgroundWithResultBlock { (ret, error) in

if(error != nil){

print("error is \(error.localizedDescription)")

}else{

print("insert successful")

}

}

}

//查询整张表的数据并输出

func getAllData(className:String){

//根据表明创建查询对象

let query = BmobQuery(className: className)

//获取表中所有的数据

query.findObjectsInBackgroundWithBlock { (allObjects, error) in

print(allObjects)

}

}

//按条件查询(表名,列名,查询约束条件),并输出结果

func getDataWithKey(className:String,lineName:String,queryItem:String){

//根据表明创建查询对象

let query = BmobQuery(className: className)

//添加约束(whereKey有许多重载方法,比如notEqualTo等等)

query.whereKey(lineName, equalTo: queryItem)

//开始查询

query.findObjectsInBackgroundWithBlock { (allObjects, error) in

if(error != nil){

print("error is \(error.localizedDescription)")

}else{

print(allObjects)

}

}

}

//按条件查询(表名,列名,查询约束条件),并删除

func getDataWithKeyAndDelete(className:String,lineName:String,queryItem:String){

let query = BmobQuery(className: className)

query.whereKey(lineName, equalTo: queryItem)

query.findObjectsInBackgroundWithBlock { (allObjects, error) in

if(error != nil){

print("error is \(error.localizedDescription)")

}else{

for item in allObjects{

item.deleteInBackgroundWithBlock({ (ret, error) in

if ret{

print("delete successful")

}

})

}

}

}

}

//按条件查询(表名,列名,查询约束条件,更新的列,更新的内容),并更新

func getDataWithKeyAndUpdate(className:String,lineName:String,queryItem:String,newLine:String,newContent:String){

let query = BmobQuery(className: className)

query.whereKey(lineName, equalTo: queryItem)

query.findObjectsInBackgroundWithBlock { (allObjects, error) in

if(error != nil){

print("error is \(error.localizedDescription)")

}else{

for item in allObjects{

item.setObject(newContent, forKey: newLine)

//4.保存

item.updateInBackgroundWithResultBlock({ (ret, error) in

if(error != nil){

print("error is \(error.localizedDescription)")

}else{

print("update successful")

}

})

}

}

}

}

//上传文件至bmob

func uploadFile(file:BmobFile){

print("start upload")

//储存至云端

file.saveInBackground{ (ret, error) in

if(error != nil){

print("error is \(error.localizedDescription)")

}else{

print(file.url)//文件的地址

}

}

}

 


其中,whereKey()的重载方法有很多,具体用法请看这里:

https://docs.bmob.cn/ios/developdoc/?menukey=develop_doc&key=develop_ios#index_%87%F6%A1%06

(这里面的代码都是OC的,但是有所有whereKey重载方法的用法,我相信大家能看懂)

有了以上增删改查以及上传文件的方法,大家就可以愉快地用swift对于bmob后端云进行操作了~

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网