Upload photos to Mastodon
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func upload(user: User?, asset: PHAsset?) -> Future<Attachment, TendonError> { | |
let promise = Promise<Attachment, TendonError>() | |
guard let user = user else { | |
promise.failure(TendonError.invalidUser) | |
return promise.future | |
} | |
guard let asset = asset else { | |
promise.failure(TendonError.argument) | |
return promise.future | |
} | |
imageManager.requestImageData(for: asset, options: nil) { (imageData, _, orientation, info) in | |
let urlString = user.serverName + "/api/v1/media" | |
Alamofire.upload(multipartFormData: { (data) in | |
data.append(imageData!, withName: "file", fileName: "\(UUID.init().uuidString).png", mimeType: "image/png") // png format! | |
}, usingThreshold: UInt64.init(), to: URL(string: urlString)!, method: .post, headers: ["Authorization": "Bearer " + user.oauthToken], encodingCompletion: { (result) in | |
switch result { | |
case .success(let upload, _, _): | |
upload.responseData(completionHandler: { (dataResponse) in | |
guard | |
let data = dataResponse.data, | |
let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) | |
else { | |
promise.failure(TendonError.library) | |
return | |
} | |
guard | |
let httpResponse = dataResponse.response as? HTTPURLResponse, | |
httpResponse.statusCode == 200 | |
else { | |
let mastodonError = MastodonError(json: jsonObject) | |
promise.failure(TendonError.library) | |
return | |
} | |
promise.success(Attachment(from: jsonObject as! JSONDictionary)!) | |
}) | |
break | |
default: | |
break | |
} | |
}) | |
} | |
return promise.future | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment