Upload video to server by using Alamofire - swift

I used alamofire to upload the chosen image to the server and It's working but now I don't know how I can make the same thing for the selected video from device after select it and store the path of this video at variable , how I can use alamofire to upload this video to server ?
My code:
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 class:
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
}
}

Related

How to use a stored url from Firebase Database as an image in an UIImageView

I'm new to coding and trying to build an iOS App. I am storing images uploaded by users into my firebase storage and then saving the URL as a string ("https//.....). I am able to get a snapshot to show up in project terminal after I use print(snapshot). It prints, snap (profileImageUrl) https://firebasestorage.... How do I use this snapshot to get the ImageView to show the profile picture most recently saved?
import UIKit
import Firebase
import SDWebImage
class EditProfileViewController: UIViewController {
#IBOutlet weak var ProfileImage: UIImageView!
var selectedImage: UIImage?
var ref:DatabaseReference?
var databaseHandle:DatabaseHandle = 0
var postProfileImage = [String]()
let dbref = Database.database().reference()
let uid = Auth.auth().currentUser?.uid
override func viewDidLoad() {
super.viewDidLoad()
self.ref?.child("users").child(Auth.auth().currentUser!.uid).child("profileImageUrl").observe(.value, with: { (snapshot) in
print(snapshot)
})
ProfileImage.layer.borderWidth = 3.0
ProfileImage.layer.masksToBounds = false
ProfileImage.layer.borderColor = UIColor.white.cgColor
ProfileImage.layer.cornerRadius = ProfileImage.frame.size.width / 2
ProfileImage.clipsToBounds = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(EditProfileViewController.handleSelectProfileImageView))
ProfileImage.addGestureRecognizer(tapGesture)
ProfileImage.isUserInteractionEnabled = true
}
#objc func handleSelectProfileImageView() {
let pickerController = UIImagePickerController()
pickerController.delegate = self
present(pickerController, animated: true, completion: nil)
}
#IBAction func Cancel(_ sender: UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
let user = Auth.auth().currentUser
let fileData = NSData()
#IBAction func DoneButton(_ sender: UIBarButtonItem) {
guard let imageSelected = self.ProfileImage.image else {
print ("Avatar is nil")
return
}
var dict: Dictionary<String, Any> = [
"profileImageUrl": "",
]
guard let imageData = imageSelected.jpegData(compressionQuality: 0.4) else {
return
}
let storageRef = Storage.storage().reference(forURL: "(I have my storage url here")
let imageName = NSUUID().uuidString
let storageProfileRef = storageRef.child("Profile_Images").child(Auth.auth().currentUser!.uid).child("\(imageName).png")
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"
storageProfileRef.putData(imageData, metadata: metadata, completion:
{ (StorageMetadata, error) in
if (error != nil) {
return
}
storageProfileRef.downloadURL { (url, error) in
if let metaImageUrl = url?.absoluteString {
dict["profileImageUrl"] = metaImageUrl
Database.database().reference().child("users").child(Auth.auth().currentUser!.uid).updateChildValues(dict, withCompletionBlock: {
(error, ref) in
if error == nil {
print("Done")
}
}
)
}
}
})
dismiss(animated: true, completion: nil)
}
}
extension EditProfileViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
//print("did Finish Picking Media")
if let image = info[UIImagePickerController.InfoKey(rawValue: "UIImagePickerControllerOriginalImage")] as? UIImage{
selectedImage = image
ProfileImage.image = image
}
dismiss(animated: true, completion: nil)
}
}
I could really use some help!
You can add an extension to UIImageView as below:
extension UIImageView {
func load(url: URL, onLoadCompletion: ((_ isImageLoaded: Bool) -> Void)? = nil) {
self.image = nil
DispatchQueue.global().async { [weak self] in
if let data = try? Data(contentsOf: url) {
if let image = UIImage(data: data) {
DispatchQueue.main.async {
self?.image = image
onLoadCompletion?(true)
}
} else {
onLoadCompletion?(false)
}
} else {
onLoadCompletion?(false)
}
}
}
}
Assuming your image view outlet is something like this:
#IBOutlet weak var imageView: UIImageView!
Below is the usage when adding a loader:
if let url = URL(string: "https://firebase-storage-url") {
// show a loader here if needed
imageView.load(url: url) { (imageLoaded) in
if imageLoaded {
// hide loader
} else {
// show a place holder image
// hide loader
}
}
} else {
// show a default image
}
Below is the usage without any extra work and just loading the image:
if let url = URL(string: "https://firebase-storage-url") {
imageView.load(url: url)
}

How to send multiple images to Firebase and retrieve them in the UIImageView in Swift

I have an app that lets users choose multiple images. The problem is that it doesn't upload and save the image to the user in Firebase and retrieve the image.
This is my code:
import UIKit
import Photos
import Firebase
import BSImagePicker
class Downloadimages: UIViewController {
#IBOutlet weak var imgView: UIImageView!
var ref: DatabaseReference?
var SelectedAssets = [PHAsset]()
var PhotoArray = [UIImage]()
override func viewDidLoad() {
super.viewDidLoad()
ref = Database.database().reference()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func addImagesClicked(_ sender: Any) {
// create an instance
let vc = BSImagePickerViewController()
//display picture gallery
self.bs_presentImagePickerController(vc, animated: true,
select: { (asset: PHAsset) -> Void in
}, deselect: { (asset: PHAsset) -> Void in
// User deselected an assets.
}, cancel: { (assets: [PHAsset]) -> Void in
// User cancelled. And this where the assets currently selected.
}, finish: { (assets: [PHAsset]) -> Void in
// User finished with these assets
for i in 0..<assets.count
{
self.SelectedAssets.append(assets[i])
}
self.convertAssetToImages()
}, completion: nil)
let image = UIImagePickerController()
image.delegate = self as? UIImagePickerControllerDelegate & UINavigationControllerDelegate
image.sourceType = UIImagePickerControllerSourceType.photoLibrary
image.allowsEditing = false
self.present(image, animated: true)
{
//after its completed
}
}
#objc(imagePickerController:didFinishPickingMediaWithInfo:) func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
{
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage
{
imgView.image = image
}
else
{
//error
}
self.dismiss(animated: true, completion: nil)
let storageRef = Storage.storage().reference().child("myImage.png")
if let uploadData = UIImagePNGRepresentation(self.imgView.image!){
storageRef.putData(uploadData, metadata: nil, completion:
{
(metadata, error) in
if error != nil {
print("error")
return
}
print(metadata!)
//how do I put the download URL in the metadata into my database
}
)
}
}
func convertAssetToImages() -> Void {
if SelectedAssets.count != 0{
for i in 0..<SelectedAssets.count{
let manager = PHImageManager.default()
let option = PHImageRequestOptions()
var thumbnail = UIImage()
option.isSynchronous = true
manager.requestImage(for: SelectedAssets[i], targetSize: CGSize(width: 200, height: 200), contentMode: .aspectFill, options: option, resultHandler: {(result, info)->Void in
thumbnail = result!
})
let data = UIImageJPEGRepresentation(thumbnail, 0.7)
let newImage = UIImage(data: data!)
self.PhotoArray.append(newImage! as UIImage)
}
self.imgView.animationImages = self.PhotoArray
self.imgView.animationDuration = 3.0
self.imgView.startAnimating()
}
print("complete photo array \(self.PhotoArray)")
}
}
and this is my post code
import Foundation
class Post {
var id:String
var author:UserProfile
var text:String
var createdAt:Date
init(id:String, author:UserProfile,text:String,timestamp:Double) {
self.id = id
self.author = author
self.text = text
self.createdAt = Date(timeIntervalSince1970: timestamp / 1000)
}
static func parse(_ key:String, _ data:[String:Any]) -> Post? {
if let author = data["author"] as? [String:Any],
let uid = author["uid"] as? String,
let username = author["username"] as? String,
let photoURL = author["photoURL"] as? String,
let url = URL(string:photoURL),
let text = data["text"] as? String,
let timestamp = data["timestamp"] as? Double {
let userProfile = UserProfile(uid: uid, username: username, photoURL: url)
return Post(id: key, author: userProfile, text: text, timestamp:timestamp)
}
return nil
}
}
this is my userProfile
import Foundation
class UserProfile {
var uid:String
var username:String
var photoURL:URL
init(uid:String, username:String,photoURL:URL) {
self.uid = uid
self.username = username
self.photoURL = photoURL
}
}
and this is
import Foundation
import Firebase
class UserService {
static var currentUserProfile:UserProfile?
static func observeUserProfile(_ uid:String, completion: #escaping ((_ userProfile:UserProfile?)->())) {
let userRef = Database.database().reference().child("users/profile/\(uid)")
userRef.observe(.value, with: { snapshot in
var userProfile:UserProfile?
if let dict = snapshot.value as? [String:Any],
let username = dict["username"] as? String,
let photoURL = dict["photoURL"] as? String,
let url = URL(string:photoURL) {
userProfile = UserProfile(uid: snapshot.key, username: username, photoURL: url)
}
completion(userProfile)
})
}
}

How to pass data from view controller to data model in swift

I am building a simple app that talks to a web service.
I have used the delegates method to communicate data (from my model to view controller).
But I am not sure how to read the data from view controller (text_field.text) in my model. I need to do that so that I can pass the right parameter to my webservice
my view controller is:
import UIKit
class ViewController: UIViewController,HomeModelDelegate {
var homeModel = HomeModel()
#IBOutlet weak var loginid: UITextField!
#IBOutlet weak var pwd: UITextField!
#IBAction func submit(_ sender: UIButton) {
homeModel.chkpwd()
//Here viewcontroller is assigning itself to the homemodel's delegate property
homeModel.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
loginid.layer.cornerRadius=10
pwd.layer.cornerRadius = 10
}
func itemsDownloaded(locations: [Location]) {
loginid.text = locations[0].pwd
}
}
My model code is:
import UIKit
protocol HomeModelDelegate{
func itemsDownloaded(locations:[Location])
}
class HomeModel: NSObject
{
var delegate:HomeModelDelegate?
func chkpwd()
{
//Hit the webservice url
let x = ViewController()
let z = x.loginid
let serviceUrl = "http://www.xyz.in/webservice.php?loginid=(loginid.text)"
//download the json data
let url = URL(string: serviceUrl)
if let url = url {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url, completionHandler:
{ (data, response, error) in
if error == nil {
//succeeded
self.parseJson(data!)
}
else {
//failed
}
})
task.resume()
}
}
func parseJson(_ data:Data){
var locArray = [Location]()
do{
let jsonArray = try JSONSerialization.jsonObject(with: data, options: []) as! [Any]
for jsonResult in jsonArray{
let jsonDict = jsonResult as! [String:String]
let loc = Location(pwd: jsonDict["loginid"]!, loginid: jsonDict["pwd"]!)
locArray.append(loc)
//pass the location back to the delegate
delegate?.itemsDownloaded(locations: locArray)
}
}
catch{
print("An error occured")
}
}
}
Please try this :
import UIKit
class ViewController: UIViewController,HomeModelDelegate {
var homeModel = HomeModel()
#IBOutlet weak var loginid: UITextField!
#IBOutlet weak var pwd: UITextField!
#IBAction func submit(_ sender: UIButton) {
homeModel.z = loginid.text! // ASSIGNING z here
homeModel.chkpwd()
//Here viewcontroller is assigning itself to the homemodel's delegate property
homeModel.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
loginid.layer.cornerRadius=10
pwd.layer.cornerRadius = 10
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func itemsDownloaded(locations: [Location]) {
loginid.text = locations[0].pwd
}
}
Model :
import UIKit
protocol HomeModelDelegate{
func itemsDownloaded(locations:[Location])
}
class HomeModel: NSObject
{
var z:String = "" // INITIALIZING z
var delegate:HomeModelDelegate?
func chkpwd()
{
print(z) // CALLING z
//Hit the webservice url
let serviceUrl = "http://www.xyz.in/webservice.php?loginid=(loginid.text)"
//download the json data
let url = URL(string: serviceUrl)
if let url = url {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url, completionHandler:
{ (data, response, error) in
if error == nil {
//succeeded
self.parseJson(data!)
} else {
//failed
}
})
task.resume()
}
}
func parseJson(_ data:Data){
var locArray = [Location]()
do{
let jsonArray = try JSONSerialization.jsonObject(with: data, options: []) as! [Any]
for jsonResult in jsonArray{
let jsonDict = jsonResult as! [String:String]
let loc = Location(pwd: jsonDict["loginid"]!, loginid: jsonDict["pwd"]!)
locArray.append(loc)
//pass the location back to the delegate
delegate?.itemsDownloaded(locations: locArray)
}
} catch {
print("An error occured")
}
}
}

AVPlayer is not working when I'm trying to use with this YTVimeoExtractor

When I try to play the video through the AVPlayer, the video loads for some time(the loading symbol appears at the top of the player) then suddenly it stops and the play icon with a crossover is shown. Don't know what is wrong? I can get the video informations but I can't make the video to play.
I will show what I have done. Could anyone answer my question, help is much appreciated.
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
var playerVC : AVPlayerViewController!
var playerItem : AVPlayerItem!
var player : AVPlayer!
var playerLayer: AVPlayerLayer!
#IBOutlet weak var videoURL: UITextField!
#IBOutlet weak var videoTitle: UILabel!
#IBAction func playVideo(sender: AnyObject) {
YTVimeoExtractor.sharedExtractor().fetchVideoWithVimeoURL(self.videoURL.text!, withReferer: nil, completionHandler: {(video, error) -> Void in
if video != nil {
// https://vimeo.com/165891648
self.videoTitle.text = video?.title
print("hello: \(self.videoTitle.text)")
let url = NSURL(string: self.videoURL.text!)
// let url = NSURL.init(fileURLWithPath: self.videoURL.text!)
self.playerItem = AVPlayerItem.init(URL: url!)
self.player = AVPlayer.init(playerItem: self.playerItem)
self.playerVC = AVPlayerViewController.init();
self.playerVC.player = self.player;
self.player.currentItem!.playbackLikelyToKeepUp
self.presentViewController(self.playerVC, animated: true) { () -> Void in
self.playerVC.player?.play()
}
}else {
let alert = UIAlertController(title: error!.localizedDescription, message: error!.localizedFailureReason, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
})
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(animated: Bool) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
This is the one I get on the simulator.
I used this https://github.com/lilfaf/YTVimeoExtractor one to do this sample project. You can try it out and let me know.
I had the same issue and fix using this way:
#IBAction func btnDownload_touchUpInside(_ sender: UIButton) {
YTVimeoExtractor.shared().fetchVideo(withVimeoURL: self.videoURL.text!, withReferer: nil, completionHandler: {(video, error) -> Void in
if video != nil {
self.videoTitle.text = video?.title
if let streamUrls = video?.streamURLs
{
var streamURL: String?
var streams : [String:String] = [:]
for (key,value) in streamUrls {
streams["\(key)"] = "\(value)"
print("\(key) || \(value)")
}
if let large = streams["720"]
{
streamURL = large
}
else if let high = streams["480"]
{
streamURL = high
}
else if let medium = streams["360"]
{
streamURL = medium
}
else if let low = streams["270"]
{
streamURL = low
}
if let url = streamURL
{
Alamofire.download(url, to: { (temporaryURL, response) -> (destinationURL: URL, options: DownloadRequest.DownloadOptions) in
if let directoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as? NSURL {
let fileName = response.suggestedFilename!
let finalPath = directoryURL.appendingPathComponent(fileName)
self.downloadedVideoPath = finalPath?.absoluteString
return (finalPath!, DownloadRequest.DownloadOptions(rawValue: 2))
}
}).downloadProgress(closure: { (progress) in
print("Progress: \(progress.fractionCompleted)")
})
}
}
}
})
}
#IBAction func btnPlayOffLine_touchUpInside(_ sender: UIButton) {
YTVimeoExtractor.shared().fetchVideo(withVimeoURL: self.videoURL.text!, withReferer: nil, completionHandler: {(video, error) -> Void in
if video != nil {
let videoURL = NSURL(string: self.downloadedVideoPath!)
let player = AVPlayer(url: videoURL! as URL)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
playerViewController.player!.play()
}
}
})
}
#IBAction func btnPlayOnLine_touchUpInside(_ sender: UIButton) {
YTVimeoExtractor.shared().fetchVideo(withVimeoURL: self.videoURL.text!, withReferer: nil, completionHandler: {(video, error) -> Void in
if video != nil {
self.videoTitle.text = video?.title
if let streamUrls = video?.streamURLs
{
var streamURL: String?
var streams : [String:String] = [:]
for (key,value) in streamUrls {
streams["\(key)"] = "\(value)"
print("\(key) || \(value)")
}
if let large = streams["720"]
{
streamURL = large
}
else if let high = streams["480"]
{
streamURL = high
}
else if let medium = streams["360"]
{
streamURL = medium
}
else if let low = streams["270"]
{
streamURL = low
}
if let url = streamURL
{
let videoURL = NSURL(string: url)
let player = AVPlayer(url: videoURL! as URL)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
playerViewController.player!.play()
}
}
}
}
})
}
}

How to call the view controller from another view controller programmatically depending on the response from the remote server

In my app I take the server credentials in the main view controller (loginViewController.swift). When I click on 'Login' button on the 'loginViewController', its shows the app logoViewController which has the activity indicator view and the credentials value is passed to the remote server over https connection. I get a JSON array in the response from remote server which consist of message "Successful : 1" or "Unsuccessful : 0" with other app details.
For the value '1' in the JSON array I want to show the menuViewController screen and for the value '0' I want to show the RegisterViewController screen for further process in the app.
Calling of 'menuViewController'/'RegisterViewController' should happen in the background process of the 'logoViewController'.
If have tried the following code given bellow, but unable to call the 'menuViewController'/'RegisterViewController'.
Please let me know were I went wrong. Is the UIStoryboard approach is right?
Any suggestion or links or tutorial will be helpful.
import UIKit
class logoViewController: UIViewController {
#IBOutlet weak var act: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
self.act.startAnimating()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// syncreq function is called from the connectionViewController.
// connectionViewController is the common class for connecting to the remote server
func syncreq (JSONdata: AnyObject) { // Proceesing for PRMS response
// Getting the value from the JSON
var Successful = self.getIntFromJSON(JSONdata as NSDictionary, key: "Successful")
println("Value of Successful : \(Successful)")
if (Successful == 0){
//let secondViewController = self.storyboard?.instantiateViewControllerWithIdentifier("registrationID") as regVC
//self.navigationController?.pushViewController(secondViewController, animated: true)
//performSegueWithIdentifier("registrationID", sender: self)
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
var setViewController = mainStoryboard.instantiateViewControllerWithIdentifier("registrationID") as RegisterViewController
self.presentViewController(setViewController, animated: false, completion: nil)
}
else if (Successful == 1){
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
var setViewController = mainStoryboard.instantiateViewControllerWithIdentifier("mnuID") as menuViewController
self.presentViewController(setViewController, animated: false, completion: nil)
}
}
func getIntFromJSON(data: NSDictionary, key: String) -> Int {
let info : AnyObject? = data[key]
// println("Value of data[key] : \(key)")
if let info = data[key] as? Int {
println("Value of value for \(key) : \(info)")
return info
}
else {
return 0
}
}
}
Thanks in advance
I have implemented a common function that will callback the calling function on the response from the remote server.
Following is the function which I have implemented.
func connect(jsonString:NSDictionary) -> NSDictionary
{
var JSONdata: AnyObject = ["" : ""] as Dictionary<String, String>
println("------------------Function connserv")
let prefs = NSUserDefaults.standardUserDefaults()
var conn_timeout: AnyObject = prefs.objectForKey("conn_timeout")!
var numberFormatter = NSNumberFormatter()
var number:NSNumber? = numberFormatter.numberFromString(conn_timeout as! String)
if let number = number {
var integer = Int(number)
println("\(integer)")
}
var recon_maxcount: AnyObject = prefs.objectForKey("recon_maxcount")!
println("recon_maxcount in Connection : \(recon_maxcount)")
println("conn_timeout in Connection : \(conn_timeout)")
var recon_interval: AnyObject = prefs.objectForKey("recon_interval")!
println("recon_interval in Connection : \(recon_interval)")
var number1:NSNumber? = numberFormatter.numberFromString(recon_maxcount as! String)
if let number1 = number1 {
var integer1 = Int(number1)
println("\(integer1)")
}
var number2:NSNumber? = numberFormatter.numberFromString(recon_interval as! String)
//if let number2 = number2 {
var integer2 = Int(number2!)
var xval = UInt32(integer2)
println("\(xval)")
//}
var IP: AnyObject = prefs.objectForKey("IP")!
var port: AnyObject = prefs.objectForKey("Port")!
println("IP in Connection : \(IP)")
println("port in Connection : \(port)")
prefs.synchronize()
println("HTTP request jsonString : \(jsonString)")
var request = NSMutableURLRequest(URL: NSURL(string: "https://\(IP):\(port)/")!)
var response: NSURLResponse?
var error: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(jsonString, options: nil, error: &error)
request.timeoutInterval = (number as! NSTimeInterval)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
//request.setValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("gzip", forHTTPHeaderField: "Accept-encoding")
println("Firing synchronous url connection......")
println(request)
//println("Before======\(i)!")
for (var i = 0; i < number1 as! Int ; i++)
{
var error: NSError?
println("Try connecting to server: \(NSDate())")
let urlData = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
//println("response : \(response)")
//println("error : \(error)")
if error != nil || urlData!.length == 0
{
println("Error happend timeout======\(error?.code)!")
println(NSDate())
sleep(xval as UInt32)
//println("NSDate()")
JSONdata = ["0" : "0"] as Dictionary<String, String>
continue
}
else
{
println("Successfully connected : \(NSDate())")
println("\(urlData!.length) bytes of data was returned")
println(response!);
if let httpResponse = response as? NSHTTPURLResponse {
println("Status Code ------------------------------------>\(httpResponse.statusCode)")
}
println(NSString(data: urlData!, encoding: NSUTF8StringEncoding)!)
var er: NSError?
let JSONresdata: AnyObject = (NSJSONSerialization.JSONObjectWithData(urlData!, options: .MutableContainers,error: &er)!)
println("==========================================================================================")
println("JSON response : \(JSONresdata)")
JSONdata = JSONresdata as! NSDictionary
break
}
}
println("out of for loop : \(JSONdata)")
return JSONdata as! NSDictionary;
}