我使用alamofire将所选图像上传到服务器并且它正在工作但现在我不知道如何在选择它之后如何从设备为所选视频制作相同的内容并将该视频的路径存储在变量中,我如何使用alamofire将此视频上传到服务器?
我的代码:
import UIKit
import Alamofire
import AVKit
import AVFoundation
import MediaPlayer
import MobileCoreServices
class sendFinalNews: UIViewController, UIImagePickerControllerDelegate,UINavigationControllerDelegate {
@IBOutlet weak var titleText: UITextField!
@IBOutlet weak var msgDetailText: UITextView!
@IBOutlet weak var sendIndicator: UIActivityIndicatorView!
@IBOutlet weak var loadedImage: UIImageView!
var CUSTOMER_KEY = "dkeqnq9fmkhq"
var titlemsg = ""
var detailmsg = ""
var videoURL:String!
var playerViewController = AVPlayerViewController()
var playerView = AVPlayer()
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func addVideoButton(sender: AnyObject) {
var videoPickerController = UIImagePickerController()
videoPickerController.delegate = self
videoPickerController.sourceType = .SavedPhotosAlbum
videoPickerController.mediaTypes = [kUTTypeMovie as String]
self.presentViewController(videoPickerController, animated: true, completion: nil)
}
@IBAction func addImageButton(sender: AnyObject) {
let ImagePicker = UIImagePickerController()
ImagePicker.delegate = self
ImagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(ImagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let mediaType = info[UIImagePickerControllerMediaType] as! NSString
let url = info[UIImagePickerControllerMediaURL]
print(url)
if mediaType.isEqualToString(kUTTypeImage as String)
{
loadedImage.image = info[UIImagePickerControllerOriginalImage] as? UIImage
}
else if mediaType.isEqualToString(kUTTypeMovie as String)
{
let urlOfVideo = info[UIImagePickerControllerMediaURL] as? NSURL
if let url = urlOfVideo {
print("video loadaed")
videoURL = String(urlOfVideo)
print(videoURL)
}
}
self.dismissViewControllerAnimated(true, completion: nil )
}
@IBAction func backButton(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil )
}
@IBAction func sendButton(sender: AnyObject) {
titlemsg = titleText.text!
detailmsg = msgDetailText.text!
self.sendIndicator.startAnimating()
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
// ...
// heavy loop codes here
// ...
self.uploadFile()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.sendIndicator.stopAnimating()
})
});
}
func uploadFile() {
//let image = UIImage(named: "ios9.jpg")
let newimage : NSData = UIImageJPEGRepresentation(loadedImage.image!, 32)!
let newRandomName = randomStringWithLength(32)
let fname = (newRandomName as String) + ".jpg"
let parameters = [
"pic" :NetData(data: newimage, mimeType: .ImageJpeg, filename: fname),
"msg" :self.detailmsg,
"customer_key" : self.CUSTOMER_KEY
]
let urlRequest = self.urlRequestWithComponents("myURLhere", parameters: parameters)
Alamofire.upload(urlRequest.0, data: urlRequest.1)
.progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
print("\(totalBytesWritten) / \(totalBytesExpectedToWrite)")
}
.responseJSON { response in
debugPrint(response)
}
}
func urlRequestWithComponents(urlString:String, parameters:NSDictionary) -> (URLRequestConvertible, NSData) {
// create url request to send
let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: urlString)!)
mutableURLRequest.HTTPMethod = Alamofire.Method.POST.rawValue
//let boundaryConstant = "myRandomBoundary12345"
let boundaryConstant = "NET-POST-boundary-\(arc4random())-\(arc4random())"
let contentType = "multipart/form-data;boundary="+boundaryConstant
mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")
// create upload data to send
let uploadData = NSMutableData()
// add parameters
for (key, value) in parameters {
uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
if value is NetData {
// add image
let postData = value as! NetData
//uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"; filename=\"\(postData.filename)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
// append content disposition
let filenameClause = " filename=\"\(postData.filename)\""
let contentDispositionString = "Content-Disposition: form-data; name=\"\(key)\";\(filenameClause)\r\n"
let contentDispositionData = contentDispositionString.dataUsingEncoding(NSUTF8StringEncoding)
uploadData.appendData(contentDispositionData!)
// append content type
//uploadData.appendData("Content-Type: image/png\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) // mark this.
let contentTypeString = "Content-Type: \(postData.mimeType.getString())\r\n\r\n"
let contentTypeData = contentTypeString.dataUsingEncoding(NSUTF8StringEncoding)
uploadData.appendData(contentTypeData!)
uploadData.appendData(postData.data)
}else{
uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!)
}
}
uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
return (Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0, uploadData)
}
func randomStringWithLength (len : Int) -> NSString {
let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var randomString : NSMutableString = NSMutableString(capacity: len)
for (var i=0; i < len; i++){
var length = UInt32 (letters.length)
var rand = arc4random_uniform(length)
randomString.appendFormat("%C", letters.characterAtIndex(Int(rand)))
}
return randomString
}
}
NetData类:
import Foundation
import UIKit
enum MimeType: String {
case ImageJpeg = "image/jpeg"
case ImagePng = "image/png"
case ImageGif = "image/gif"
case Json = "application/json"
case Unknown = ""
func getString() -> String? {
switch self {
case .ImagePng:
fallthrough
case .ImageJpeg:
fallthrough
case .ImageGif:
fallthrough
case .Json:
return self.rawValue
case .Unknown:
fallthrough
default:
return nil
}
}
}
class NetData
{
let data: NSData
let mimeType: MimeType
let filename: String
init(data: NSData, mimeType: MimeType, filename: String) {
self.data = data
self.mimeType = mimeType
self.filename = filename
}
init(pngImage: UIImage, filename: String) {
data = UIImagePNGRepresentation(pngImage)!
self.mimeType = MimeType.ImagePng
self.filename = filename
}
init(jpegImage: UIImage, compressionQuanlity: CGFloat, filename: String) {
data = UIImageJPEGRepresentation(jpegImage, compressionQuanlity)!
self.mimeType = MimeType.ImageJpeg
self.filename = filename
}
}