How to load a video from Parse.com using swift? - ios

I'm trying to find a way to load a youtube URL string from parse.com database in my swift application. I have it so when the user clicks on a button that says video it will load the video that is connected to the URL. I can't seem to find out how to make this work though. Any Ideas on how to code this?
In the data base I have the class called Products, than the column name for the video is ProductVideo, and the button in the app is called productVideo.
edit:
// Unwrap the current object object
if let object = currentObject {
productName.text = object["ProductName"] as? String
productDescription.text = object["ProductDescription"] as! String productCategory.text = object["ProductCategory"] as? String
videoStatus.text = object["VideoStatus"] as? String var initialThumbnail = UIImage(named: "question")
ProductImage.image? = initialThumbnail!
if let thumbnail = object["ProductImage"] as? PFFile {
ProductImage.file = thumbnail
ProductImage.loadInBackground() if self.videoStatus.text == "None"{ self.productVideo.hidden = true
self.videoView.hidden = true
}
edit:
// Unwrap the current object object
if let object = currentObject {
productName.text = object["ProductName"] as? String
productDescription.text = object["ProductDescription"] as! String productCategory.text = object["ProductCategory"] as? String
videoStatus.text = object["VideoStatus"] as? String
let youtubeURL = currentObject["ProductVideo"] as! String
let url = NSURL(string: youtubeURL)
if UIApplication.sharedApplication().canOpenURL(url!) {
UIApplication.sharedApplication().openURL(url!)
}
var initialThumbnail = UIImage(named: "question")
ProductImage.image? = initialThumbnail!
if let thumbnail = object["ProductImage"] as? PFFile {
ProductImage.file = thumbnail
ProductImage.loadInBackground()
if self.videoStatus.text == "None"
{
self.productVideo.hidden = true
self.videoView.hidden = true
}

If you have the URL like you say you do, then you can
let youtubeURL = parseObjeect["ProductVideo"] as String
and then
let url = NSURL(string: youtubeURL)
if UIApplication.sharedApplication().canOpenURL(url!) {
UIApplication.sharedApplication().openURL(url!)
}
Note: This will open the Youtube Video in Safari or in YouTube if the user has the App installed.

Related

How to add/use GCKMediaQueue in Swift?

So I have managed to play a video on Chromecast. But only one at a time. I've been trying to figure how to programmatically add to the queue. The idea is to keep playing videos all day. In the code below "playthisvideo()" randomly returns a string that contain an http://.....mp4 . I've look at Google's documentation, it's either too vague or I just don't understand it. And I can't seem to find any examples that would lead the way for me to follow.
func castthevideo() {
let metadata = GCKMediaMetadata()
metadata.setString("Los Simpsons", forKey: kGCKMetadataKeyTitle)
metadata.setString ("Barista: ¿Cómo tomas tu café? " +
" Yo: Muy, muy en serio.",
forKey: kGCKMetadataKeySubtitle)
metadata.addImage(GCKImage(url: URL(string: "https://m.media-amazon.com/images/M/MV5BYjFkMTlkYWUtZWFhNy00M2FmLThiOTYtYTRiYjVlZWYxNmJkXkEyXkFqcGdeQXVyNTAyODkwOQ##._V1_.jpg")!,
width: 480,
height: 360))
let PTV = playthisvideo()
let url = URL.init(string: PTV)
print ("****** ", PTV)
guard let mediaURL = url else {
print("****** invalid mediaURL")
return }
//let mediaInfoBuilder = GCKMediaInformationBuilder.init(contentURL: mediaURL)
let mediaInfoBuilder = GCKMediaInformationBuilder.init(contentURL: mediaURL)
mediaInfoBuilder.streamType = GCKMediaStreamType.none;
mediaInfoBuilder.contentType = "video/mp4"
mediaInfoBuilder.metadata = metadata;
let mediaInformation = mediaInfoBuilder.build()
if let request = sessionManager.currentSession?.remoteMediaClient?.loadMedia(mediaInformation) { request.delegate = self }
GCKCastContext.sharedInstance().presentDefaultExpandedMediaControls()
}
func castanthor(byAppending appending: Bool) {
let PTV = playthisvideo()
let url = URL.init(string: PTV)
guard let mediaURL = url else {
print("invalid mediaURL")
return
}
myNSNumber = (1 as NSNumber)
if let remoteMediaClient = GCKCastContext.sharedInstance().sessionManager.currentCastSession?.remoteMediaClient {
let builder = GCKMediaQueueItemBuilder()
builder.mediaInformation = selectedItem.mediaInfo
builder.autoplay = true
builder.preloadTime = 3
let item = builder.build
if remoteMediaClient.mediaStatus != nil, appending {
let request = remoteMediaClient.queueInsert(item(), beforeItemWithID: kGCKMediaQueueInvalidItemID)
request.delegate = self
} else {
let options = GCKMediaQueueLoadOptions()
options.repeatMode = remoteMediaClient.mediaStatus?.queueRepeatMode ?? .off
let request = castSession.remoteMediaClient?.queueLoad([item()], with: options)
request?.delegate = self
}
}}
var mediaItems = [GCKMediaQueueItem]()
var urls = // Array of only audio and videos
for index in 0..<urls.count {
let builder = GCKMediaQueueItemBuilder()
let mediaInfoBuilder = GCKMediaInformationBuilder.init(contentURL: urls[i])
mediaInfoBuilder.streamType = GCKMediaStreamType.none;
mediaInfoBuilder.contentType = "video/mp4"
mediaInfoBuilder.metadata = metadata;
let mediaInformation = mediaInfoBuilder.build()
builder.mediaInformation = mediaInformation
builder.autoplay = true
builder.preloadTime = 3
let item = builder.build
mediaItems.append(item)
}
if let remoteMediaClient = GCKCastContext.sharedInstance().sessionManager.currentCastSession?.remoteMediaClient {
let loadOptions = GCKMediaQueueLoadOptions()
loadOptions.repeatMode = .all
loadOptions.startPosition = 0
remoteMediaClient.queueLoadItems(mediaItems, withOptions:loadOptions)
}

How to download image from JSON using the Swift 3 and Alamofire?

How to download image from JSON using Alamofire and Swift 3? I am getting dictionary of data. See the following JSON response. I am able to print data in labels but I can't download the image. This is the response I am getting from the API.
userJson userJson userJson userJson ["status": 1, "student": { "admission_date" = "14/06/2017";
"admission_no" = 13538; "class_teacher" = "Caroline Forbes"; dob =
"04/05/2001"; email = "ranisagar.sivadas#gmail.com"; "father_name" =
"SAGAR SIVADAS"; gender = Male; image =
"/system/images/86/j1f9DiJi_medium.jpg?1504593436"; "mother_name" =
"RANI R S"; name = "Abhijith Sagar"; phone = 9066260799; religion =
Hindu; "school_email" = "13538.861#demo.in"; "student_id" = 86; },
"message": Details fetched successfully.]
This is my code.
func SetUpUIProfiledata() {
APIManager.sharedInstance.getParentDataFromURL(){(userJson)-> Void in
let swiftyJsonVar = JSON(userJson)
print("userJson userJson userJson userJson",userJson)
print("swiftyJsonVar",swiftyJsonVar)
let message = swiftyJsonVar["message"].rawString()
let sudent = swiftyJsonVar["student"].rawString()!
let jsonData = sudent.data(using: .utf8)!
let dictionary = try? JSONSerialization.jsonObject(with: jsonData, options: []) as! Dictionary<String, Any>
self.name_lbl.text = dictionary?["name"] as? String
self.fatherName_lbl.text = dictionary?["father_name"] as? String
self.motherName_lbl.text = dictionary?["mother_name"] as? String
self.phone_lbl.text = dictionary?["phone"] as? String
self.email_lbl.text = dictionary?["email"] as? String
self.dob_lbl.text=dictionary?["dob"] as? String
self.gender_lbl.text=dictionary?["gender"] as? String
self.religion_lbl.text=dictionary?["religion"] as? String
self.admissionDate_lbl.text=dictionary?["admission_date"] as? String
self.admissionNum_lbl.text=dictionary?["admission_no"] as? String
self.schoolMail_lbl.text=dictionary?["school_email"] as? String
self.teacher_lbl.text=dictionary?["class_teacher"] as? String
}
}
Have a look at below code you just need to pass a link url to alamofire and you can download a image . if its not the expected answer please Re edit your question .
let strURL1:String = "https://www.planwallpaper.com/static/images/9-credit-1.jpg"
Alamofire.request(strURL1).responseData(completionHandler: { response in
debugPrint(response)
debugPrint(response.result)
if let image1 = response.result.value {
let image = UIImage(data: image1)
self.imageView.image = image
}
})
I looked at output you had provided you are getting
image =
"/system/images/86/j1f9DiJi_medium.jpg?1504593436";
is this a valid url or path if its a url you need to add your base url + your " /system/images/86/j1f9DiJi_medium.jpg?1504593436" and pass it to alamofire block to download image
as in my above example
"https://www.planwallpaper.com" - baseURl
"static/images/9-credit-1.jpg" - image Path as in your case
Hope it helps.
First get the image key corresponding value & marge it with your base URL. Like
let url = "www.yourbaseurlhere.com" + "/system/images/86/j1f9DiJi_medium.jpg?1504593436"
Now create a destination path for it like
let destination = DownloadRequest.suggestedDownloadDestination(
for: .documentDirectory,
in: .userDomainMask
)
Now use Alamofire download method like
Alamofire.download(url, to: destination)
.downloadProgress { progress in
print("Download Progress: \(progress.fractionCompleted)")
}
.responseData { response in
if response.result.value != nil {
if let directoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as? URL {
let fileName = response.response?.suggestedFilename // get your file name here.
let finalPath = directoryURL.appendingPathComponent(fileName!) //get your file path here
}
}
}
Hope it helps.

Saving api Facebook data for use in different ViewController swift iOS

I'm hitting Facebook's graph to pull basic user info when the user logs in. My question is how do I use swift to save/pull that information in the best way so that it persists across the child viewcontrollers thereafter (basically everything after login). For instance, I want to use the profile pic as a settings button throughout the app after the login screen (not in it) in my login view controller I have this relevant code:
let userImageView: UIImageView = {
let imageView = UIImageView()
return imageView
}()
let nameLabel: UILabel = {
let label = UILabel()
return label
}()
and then later:
func fetchProfile() {
let parameters = ["fields": "email, first_name, last_name, picture.type(large)"]
FBSDKGraphRequest(graphPath: "me", parameters: parameters).startWithCompletionHandler({ (connection, user, requestError) -> Void in
if requestError != nil {
print(requestError)
return
}
var _ = user["email"] as? String
let firstName = user["first_name"] as? String
let lastName = user["last_name"] as? String
self.nameLabel.text = "\(firstName!) \(lastName!)"
var pictureUrl = ""
if let picture = user["picture"] as? NSDictionary, data = picture["data"] as? NSDictionary, url = data["url"] as? String {
pictureUrl = url
}
let url = NSURL(string: pictureUrl)
NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
if error != nil {
print(error)
return
}
let image = UIImage(data: data!)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.userImageView.image = image
})
}).resume()
})
}
What do I need to do to access this in my second ViewController? From what I can understand, segues only help if I have a physical attribute in the first viewController to push them from.
Thanks
The best way to save images will be with Documents Directory as Core Data is not optimized for files as large as images. You would want to save the photo in Documents Directory as so......
func saveImageDocumentDirectory(){
let fileManager = NSFileManager.defaultManager()
let paths = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString).stringByAppendingPathComponent(*** Name of DocDir Image***)
let image = // *** Your Facebook Image ***
print(paths)
let imageData = UIImageJPEGRepresentation(image!, 0.5)
fileManager.createFileAtPath(paths as String, contents: imageData, attributes: nil)
}
Then in your viewcontroller(s) create an empty public image var fbImage:UIImage() then create a getImage function and code as follows.....
func getImage()
{
let fileManager = NSFileManager.defaultManager()
let imagePAth = (self.getDirectoryPath() as NSString).stringByAppendingPathComponent(*** Name of Your DocDir Image ***)
if fileManager.fileExistsAtPath(imagePath){
self.fbImage.image = UIImage(contentsOfFile: imagePath)
}else{
print("No Image Saved")
}
}

NSURL for telephone always nil

This is my NSURL
let url = NSURL(string: "tel://\(phoneCall)")
It is always nil, although the phoneCall is a valid mobile number string, and I am testing on a real iPhone.
I tried
let url = NSURL(string: "tel:\(phoneCall)")
but it's still nil.
let phoneCall = "tel://9000002143";
let url:NSURL = NSURL(string:phoneCall);
//OR
var url:NSURL = NSURL(string: "tel://9000002143")
if phoneCall == nil || phoneCall.isEmpty
{
print("phoneCall is empty or nil.")
}
else
{
UIApplication.sharedApplication().openURL(url);
}
Where this phoneCall is set?
I had a similar issue with a optional type. This code illustrate the problem:
let user = row.value
let phone = user?.phone
let url = NSURL(string: "tel://\(phone)")
UIApplication.sharedApplication().openURL(url!)
In this case, the value of urlString variable is "tel://Optional(\"11XXXXXXXXX\")", because the user variable can be nil.
You have to ensure that the user is not nil first, something like:
guard let user = row.value else {
return
}
let phone = user.phone
let urlString = "tel://\(phone)"
let url = NSURL(string: urlString)
UIApplication.sharedApplication().openURL(url!)

SwiftyJSON - issues with parsing

I try to parse json with SwiftyJSON. One of the fields have url to image and i try to save it as NSData but I face crash and console errors. Crash appears when compiler comes to object creation
code it the following
var JSONStorage : [Article?]?
var objects = [Article?]()
override func viewDidLoad() {
super.viewDidLoad()
let number = arc4random_uniform(1000)
let urlString = "http://wirehead.ru/article.json?\(number)"
if let url = NSURL(string: urlString) {
if let data = try? NSData(contentsOfURL: url, options: []) {
let json = JSON(data: data)
for element in json["article"].arrayValue {
let id = Int(element["id"].stringValue)
let title = element["title"].stringValue
let subtitle = element["subtitle"].stringValue
let body = element["body"].stringValue
let img = element["images"]["main"].rawValue
let obj:Article = Article(id: id!, title: title, subtitle: subtitle, body: body, mainImage: img as! NSData)
objects.append(obj)
print("We are inside if let")
}
}
}
print(objects)
}
Link to JSON is http://wirehead.ru/article.json and here is with highlight http://pastebin.com/AAEFjsQN
Error that I get is
Any advice ?
["images"]["main"] contains an URL represented by a String
To get the image data, use something like this
let imgURLString = element["images"]["main"].stringValue
if let url = NSURL(string:imgURLString) {
let img = NSData(contentsOfURL:url)
}

Resources