POST image Swift 3 using Alamofire - swift

I'm trying to POST an image in Swift 3 using Alamofire. I'm not sure how I can send my image specified in my params. I think I need to save the photo to POST, correct? Is there a way to not have to save the photo first?
func postPhoto (image: UIImage) {
let url = try! URLRequest(url: URL(string:"http://example.com/doapost")!, method: .post, headers: nil)
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(Data(), withName: "image", fileName: "file.png", mimeType: "image/png")
},
with: url,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
if((response.result.value) != nil) {
print(response)
} else {
print("nil response")
}
}
case .failure( _):
print("Failure to post")
break
}
}
)
}

Related

I am trying to upload file through alamofire multipart with auth token but it is not woking

here is my code but it is giving me error here
public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
guard let myURL = urls.first else {
return
}
print("import result : \(myURL)")
let headers = ["Authorization": value!]
Alamofire.upload(
.POST, "https://api-uat.softsages.com/hr/document/upload/ownerId/e2cbe0fe31a2ff48ba7890ac23e23b8e", headers: headers, multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: "default".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"_formname")
multipartFormData.appendBodyPart(fileURL: myURL, name: "photo")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseString { response in
debugPrint(response)
}
case .Failure(let encodingError):
print(encodingError)
}
}
)
}
here I am getting error -ype of expression is ambiguous without more context. in the code above I have added file url which i am getting from document picker and according to swagger only i have to pass file as url

upload array of images with alamofire multipart

i upload array of images to server with alamofire multipart it uploades only first image (number of times array count) and doesnot upload the rest of images, i check every thing when get images from image picker to before and after appending image to multipart
extension profileViewController{
#objc private func UploadImage()
{
let headers = ["Authorization": "Bearer \(AuthService.instance.Auth_Token)"]
Alamofire.upload(multipartFormData: { multipartFormData in
if self.ImageArray?.isEmpty == false{
for (index, image) in self.ImageArray!.enumerated(){
print(index)
var imageData = image.jpegData(compressionQuality: 0.6)
print(imageData)
multipartFormData.append(imageData!, withName: "photos[]", fileName: "\(self.RandomString(length: 10)).jpeg",mimeType: "image/jpeg")
print(imageData)
imageData?.removeAll()
}
}else{
return
}
}, usingThreshold:UInt64.init(),
to: "http://couponsub.farid.azq1.com/api/save-user-photos"/*upload_imageUrl*/, //URL Here
method: .post,
headers: headers, //pass header dictionary here
encodingCompletion: { (result) in
switch result {
case .success(let upload, _, _):
print("the status code is :")
upload.uploadProgress(closure: { (progress) in
print(progress.fractionCompleted)
//self.ProgressBar.progress = CGFloat(Float(progress.fractionCompleted))
})
upload.responseJSON { response in
if response.result.isSuccess == true{
KRProgressHUD.dismiss()
}
print("the resopnse code is : \(String(describing: response.response?.statusCode))")
let json = try! JSON(data: response.data!)
print(json)
}
break
case .failure(let encodingError):
print("the error is : \(encodingError.localizedDescription)")
break
}
})
}
}
func uploadMultipleImages(imagesData:[Data]){
Alamofire.upload(multipartFormData: { multipartFormData in
// import image to request
for imageData in imagesData {
multipartFormData.append(imageData, withName: "\(imageParamName)[]", fileName: "\(Date().timeIntervalSince1970).jpeg", mimeType: "image/jpeg")
}
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
}, to: urlString,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
}
case .failure(let error):
print(error)
}
})
}

Swift - How to upload video to youtube unlisted?

I upload video to youtube from my app. But it is public now.
My question is how can I upload video as unlisted ?
here is my upload func
func postVideoToYT(videoUrl: URL, token: String,title:String,innoId:Int,videoTags:String,callback: #escaping (Bool) -> Void) {
do {
let headers = ["Authorization": "Bearer \(token)"]
let videoData = try Data(contentsOf: videoUrl)
upload(multipartFormData: { multipartFormData in
multipartFormData.append("{'snippet':{'title' : '\(title)', 'description': ''}}".data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "snippet", mimeType: "application/json")
multipartFormData.append(videoData, withName: "video", fileName: "video.mp4", mimeType: "application/octet-stream")
}, usingThreshold: 1, to: URL(string: "https://www.googleapis.com/upload/youtube/v3/videos?part=snippet")!, method: .post, headers: headers, encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
print("Post video to url --->\(response)")
if let json = response.result.value as? [String : Any] {
let videoId = json["id"] as! String
self.delayWithSeconds(1, completion: {
self.addVideo(innoId: innoId, videoKey:videoId, shortDesc: title, tagIds: videoTags)
})
}
callback(true)
}
break
case .failure(_):
callback(false)
break
}
})
}
catch {
}
}
The privacy must be passed along with the snippet
"{'snippet':{'title' : '\(title)', 'description':' \(description)', 'tags': \(keywords)},'status':{'privacyStatus' : '\(privacyStatus)'}}".data(using: .utf8, allowLossyConversion: false)!
Added the privacy to your code below.
func postVideoToYT(videoUrl: URL, token: String,title:String,innoId:Int,videoTags:String,callback: #escaping (Bool) -> Void) {
do {
let headers = ["Authorization": "Bearer \(token)"]
let videoData = try Data(contentsOf: videoUrl)
upload(multipartFormData: { multipartFormData in
multipartFormData.append("{'snippet':{'title' : '\(title)', 'description':' \(description)', 'tags': \(keywords)},'status':{'privacyStatus' : '\(privacyStatus)'}}".data(using: .utf8, allowLossyConversion: false)!, withName: "snippet", mimeType: "application/json")
multipartFormData.append(videoData, withName: "video", fileName: "video.mp4", mimeType: "application/octet-stream")
}, usingThreshold: 1, to: URL(string: "https://www.googleapis.com/upload/youtube/v3/videos?part=snippet")!, method: .post, headers: headers, encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
print("Post video to url --->\(response)")
if let json = response.result.value as? [String : Any] {
let videoId = json["id"] as! String
self.delayWithSeconds(1, completion: {
self.addVideo(innoId: innoId, videoKey:videoId, shortDesc: title, tagIds: videoTags)
})
}
callback(true)
}
break
case .failure(_):
callback(false)
break
}
})
}
catch {
}
}

Setting snippet data (Unlisted) for youtube upload via REST API using Swift

I upload video to youtube from my app. But it's public. I want to upload it unlisted. How can I do this ?
Any advice or code samples ?
func postVideoToYT(videoUrl: URL, token: String,title:String,innoId:Int,videoTags:String,callback: #escaping (Bool) -> Void) {
do {
let headers = ["Authorization": "Bearer \(token)"]
let videoData = try Data(contentsOf: videoUrl)
upload(multipartFormData: { multipartFormData in
multipartFormData.append("{'snippet':{'title' : '\(title)', 'description': ''}}".data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "snippet", mimeType: "application/json")
multipartFormData.append("{'status' : {'privacyStatus':'unlisted'}}".data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "status",mimeType: "application/json")
multipartFormData.append(videoData, withName: "video", fileName: "video.mp4", mimeType: "application/octet-stream")
}, usingThreshold: 1, to: URL(string: "https://www.googleapis.com/upload/youtube/v3/videos?part=snippet&status")!, method: .post, headers: headers, encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
print("Post video to url --->\(response)")
if let json = response.result.value as? [String : Any] {
let videoId = json["id"] as! String
self.delayWithSeconds(1, completion: {
self.addVideo(innoId: innoId, videoKey:videoId, shortDesc: title, tagIds: videoTags)
})
}
callback(true)
}
upload.uploadProgress(closure: { (progress) in
self.progressView.progress = Float(progress.fractionCompleted)
self.progressLabel.text = "\(( Int(progress.fractionCompleted * 100)))%"
})
break
case .failure(_):
callback(false)
break
}
})
}
catch {
}
}
**I think my problem is here ''https://www.googleapis.com/upload/youtube/v3/videos?part=snippet&statuspart=snippet&status''

Uploading an image using multi-part and Alamofire

I'm trying to upload an image into my backend server. A new record gets created but no images are ever uploaded:
func uploadDish(dish:Dish, completionHandler: ((AnyObject?, ErrorType?) -> Void)){
let urlString = "http://backend.com/v1/dish"
SwiftSpinner.show("Uploading Dish...")
Alamofire.upload(
.POST,
urlString,
multipartFormData: { multipartFormData in
if let image = self.image {
if let imageData : NSData = UIImageJPEGRepresentation(image, 0.1){
multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "testesttest.jpg", mimeType: "image/jpeg")
}
}
multipartFormData.appendBodyPart(data: "foo".dataUsingEncoding(NSUTF8StringEncoding)!, name :"name")
multipartFormData.appendBodyPart(data: "bar".dataUsingEncoding(NSUTF8StringEncoding)!, name :"address")
multipartFormData.appendBodyPart(data: "1".dataUsingEncoding(NSUTF8StringEncoding)!, name :"priceRange")
multipartFormData.appendBodyPart(data: "\(234)".dataUsingEncoding(NSUTF8StringEncoding)!, name :"lat")
multipartFormData.appendBodyPart(data: "\(234)".dataUsingEncoding(NSUTF8StringEncoding)!, name :"lng")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
print(upload.debugDescription)
break
case .Failure(let encodingError):
print(encodingError)
break
}
}
)
SwiftSpinner.hide()
}
It works in Postman:
This was actually correct, found out the bug was in the back end.
The above way is how you post images