Alamofire的使用教程( 二 )


2. 上传文件的时候通过来更新上传进度条:
3.当上传完成之后,通过 来更新UI
4.当上传完成之后,通过来实现跳转 。
然后 在(image:::) 的image转化之后添加以下代码:
Alamofire.upload(multipartFormData: { multipartFormData inmultipartFormData.append(imageData,withName: "imagefile",fileName: "image.jpg",mimeType: "image/jpeg")},to: "http://api.imagga.com/v1/content",headers: ["Authorization": "Basic xxx"],encodingCompletion: { encodingResult in})
记着更换Basic xxx 成你自己的 。
然后,在的闭包里面添加以下代码:
switch encodingResult {case .success(let upload, _, _):upload.uploadProgress { progress inprogressCompletion(Float(progress.fractionCompleted))}upload.validate()upload.responseJSON { response in}case .failure(let encodingError):print(encodingError)}
然后 。在.:添加以下代码
// 1.guard response.result.isSuccess else {print("Error while uploading file: \(response.result.error)")completion([String](), [PhotoColor]())return}// 2.guard let responseJSON = response.result.value as? [String: Any],let uploadedFiles = responseJSON["uploaded"] as? [[String: Any]],let firstFile = uploadedFiles.first,let firstFileID = firstFile["id"] as? String else {print("Invalid information received from service")completion([String](), [PhotoColor]())return}print("Content uploaded with ID: \(firstFileID)")// 3.completion([String](), [PhotoColor]())
这里分步介绍每一步的含义:
1. 查看请求是否成功,如果失败,打印失败信息,并且调用。
2. 分离每一部分的数据,并查看返回的状态是否有效,如果有错误,打印失败信息,并且调用。
3. 更新UI
运行项目,选择一张图片上传,可以在打印台看到以下信息:
图片
这个时候,已经完成了基本的数据上传
数据下载
接下来就是讲刚刚上传照片的分析数据下载下来 。
在的(image:::):中添加以下代码
func downloadTags(contentID: String, completion: @escaping ([String]) -> Void) {Alamofire.request("http://api.imagga.com/v1/tagging",parameters: ["content": contentID],headers: ["Authorization": "Basic xxx"]).responseJSON { response inguard response.result.isSuccess else {print("Error while fetching tags: \(response.result.error)")completion([String]())return}guard let responseJSON = response.result.value as? [String: Any] else {print("Invalid tag information received from the service")completion([String]())return}print(responseJSON)completion([String]())}}
然后(image:::) 替换 为以下代码
self.downloadTags(contentID: firstFileID) { tags incompletion(tags, [PhotoColor]())}
运行项目,上传你的文件并且查看控制台信息 。如下图:

Alamofire的使用教程

文章插图
然后返回(::) 并且替换.
下的代码为以下代码
// 1.guard response.result.isSuccess else {print("Error while fetching tags: \(response.result.error)")completion([String]())return}// 2.guard let responseJSON = response.result.value as? [String: Any],let results = responseJSON["results"] as? [[String: Any]],let firstObject = results.first,let tagsAndConfidences = firstObject["tags"] as? [[String: Any]] else {print("Invalid tag information received from the service")completion([String]())return}// 3.let tags = tagsAndConfidences.flatMap({ dict inreturn dict["tag"] as? String})// 4.completion(tags)
运行项目,上传一张图片就可以看到以下效果:
Alamofire的使用教程