Swift 异步任务后返回数据
我正在使用库上传图像。此库正在异步工作 我的职能:Swift 异步任务后返回数据,swift,Swift,我正在使用库上传图像。此库正在异步工作 我的职能: func upload() -> String { let imageData:NSData = UIImageJPEGRepresentation(pureImage!, 100)! var picture="" SRWebClient.POST("http://domain.com/upload.php") .data(imageData, fieldName:"image_field", da
func upload() -> String {
let imageData:NSData = UIImageJPEGRepresentation(pureImage!, 100)!
var picture=""
SRWebClient.POST("http://domain.com/upload.php")
.data(imageData, fieldName:"image_field", data: ["username":"test","key":"test"])
.send({(response:AnyObject!, status:Int) -> Void in
if status == 200 {
let responseJSON = response! as! Dictionary<String, AnyObject>
let s_status=responseJSON["status"] as! Int
if s_status == 1 {
picture=responseJSON["picture"] as! String
print(picture)
}
}
},failure:{(error:NSError!) -> Void in
picture=""
})
return picture
}
func upload()->字符串{
让imageData:NSData=uiImageJPEG表示(pureImage!,100)!
var picture=“”
SRWebClient.POST(“http://domain.com/upload.php")
.data(imageData,字段名:“image_字段”,数据:[“用户名”:“测试”,“键”:“测试”])
.send({(响应:AnyObject!,状态:Int)->Void in
如果状态==200{
让responseJSON=response!as!字典
设s_status=responseJSON[“status”]为!Int
如果s_状态==1{
picture=responseJSON[“picture”]作为!字符串
印刷品(图片)
}
}
},失败:{(错误:NSError!)->在中无效
picture=“”
})
返回图片
}
正如你所看到的,我必须返回图片名。但现在它总是返回空字符串,因为上传过程是异步的。上载过程后如何返回图片名称?显然,您不能将图片名称作为函数结果返回,除非您希望等待异步任务完成,并且等待将使其再次成为同步任务 有三种非常常见的方法可以使异步任务交付结果:
回调就像一个只有一个回调方法的小委托。如果您经常在移动中执行“触发并忘记”任务,并且只需要一个回调,在成功和失败时都会调用该回调;而且它只会被调用一次,并且永远不需要回收它,那么回调通常比委托更可取。它具有委托的所有优点,但更为轻量级。显然,您不能将图片名称作为函数结果返回,除非您希望等待异步任务完成,并且等待将使其再次成为同步任务 有三种非常常见的方法可以使异步任务交付结果:
func upload(completionHandler : (pictureName : NSString?)-> Void){
let imageData:NSData = UIImageJPEGRepresentation(pureImage!, 100)!
var picture=""
SRWebClient.POST("http://domain.com/upload.php")
.data(imageData, fieldName:"image_field", data: ["username":"test","key":"test"])
.send({(response:AnyObject!, status:Int) -> Void in
if status == 200 {
let responseJSON = response! as! Dictionary<String, AnyObject>
let s_status=responseJSON["status"] as! Int
if s_status == 1 {
picture=responseJSON["picture"] as! String
print(picture)
completionHandler(pictureName: picture)
}
}
},failure:{(error:NSError!) -> Void in
picture=""
completionHandler(pictureName: nil)
})
}
func upload() -> Promise<String>