尝试使用Swift在UIWebView中播放youtube

时间:2015-09-02 04:44:15

标签: ios swift youtube uiwebview

感谢您查看我的问题。

我的问题是“尝试使用后台的Swift在UIWebView中播放youtube”

在模拟器中,没有问题,我的应用程序可以在后台播放youtube视频。但是,在设备,iPhone5s,我的应用程序崩溃。

我已经把这个问题堆积了一段时间。

有人有同样的问题吗?我不知道如何解决它。

我在下面的错误。

  

2015-09-02 12:49:02.091 YoutubeApp [281:43963]无法做到   同时满足约束。

Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)     “”,

"<NSLayoutConstraint:0x170091260 V:|-(0)-[UINavigationBar:0x145546240]   (Names: '|':UIView:0x145545030 )>

Will attempt to recover by breaking constraint 

<NSLayoutConstraint:0x170091120 UINavigationBar:0x145546240.top == UIView:0x145545030.topMargin>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.

The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

(lldb)
libGPUSupportMercury.dylib`gpus_ReturnNotPermittedKillClient:
0x18c66df84 <+0>:  orr    x8, xzr, #0x1
0x18c66df88 <+4>:  movz   w9, #0xdead, lsl #16
0x18c66df8c <+8>:  movk   w9, #0xbeef
->  0x18c66df90 <+12>: str    w9, [x8]
0x18c66df94 <+16>: ret  

这是我的代码。

AppDelegate.swift

    import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        Favorite.load()
        return true
    }
func applicationWillResignActive(application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

func applicationDidEnterBackground(application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    NSNotificationCenter.defaultCenter().postNotificationName("applicationDidEnterBackground", object: nil)
}

func applicationWillEnterForeground(application: UIApplication) {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.

    NSNotificationCenter.defaultCenter().postNotificationName("applicationWillEnterForeground", object: nil)
}

func applicationDidBecomeActive(application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}

VideoPlayer.swift

 import UIKit
import MediaPlayer

class VideoPlayerViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    var fVideo:FavoriteVideo = FavoriteVideo()

    var yVideo: VideoItems = VideoItems()

    var VideoItem: AnyObject = []
    var searchItem: String = ""
    var myMoviePlayerView : MPMoviePlayerViewController!

    @IBOutlet weak var playerTableView: UITableView!
    @IBOutlet weak var favoriteText: UILabel!
    @IBOutlet weak var favoriteIcon: UIImageView!
    @IBOutlet weak var ViewWebView: UIWebView!

    var PlayVideo: playVideo = playVideo()


    override func viewDidLoad() {
    super.viewDidLoad()


    bkgVideoId.add(VideoItem as? String)
    getHTMLs(VideoItem as! String)

    updateFavoriteButton()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "viewWillEnterForeground:", name: "applicationWillEnterForeground", object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "viewDidEnterBackground:", name: "applicationDidEnterBackground", object: nil)
    // Do any additional setup after loading the view.
}

override func viewWillAppear(animated: Bool){
    super.viewWillAppear(animated)

    if searchItem != "" || searchItem == "noSearch"{
        yVideo.setYouTubeVideoInformation(KeyWord: searchItem)
    }else{
        Favorite.load()
        var favoriteIds:String = join(",", Favorite.favorites)
        fVideo.setFavoriteVideoInformation(VideoIds:favoriteIds, reset:true)

    }


    // Do any additional setup after loading the view, typically from a nib.

}


@IBAction func favoriteTapped(sender: UIButton) {
    Favorite.toggle(VideoItem as? String)
    updateFavoriteButton()

}
func updateFavoriteButton(){
    if Favorite.inFavorites(VideoItem as? String){
        favoriteIcon.image = UIImage(named: "star-on")
        favoriteText.text = "お気に入りからはずす"
    }else{
        favoriteIcon.image = UIImage(named: "blank")
        favoriteText.text = "お気に入りにいれる"
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func getHTML(VideoURL: NSString){

    var homeUrl:String = PlayVideo.makingVideoUrl(VideoURL as! String)


    ViewWebView.allowsInlineMediaPlayback = true
    ViewWebView.loadHTMLString(homeUrl, baseURL: nil)
}


func getHTMLs(VideoId:String){

    let API_KEY:String =  "AIzaSyDas3_ozKWvguhM9HyFuz83ueA1z96snvQ"
    let script:String = "<html><body style='margin:0px;padding:0px;'><script type='text/javascript' src='https://www.youtube.com/iframe_api'></script><script type='text/javascript'>var playlist = ['\(VideoId)\'];var ytplayer;function onYouTubeIframeAPIReady(){ytplayer=new YT.Player('playerId',{events:{'onReady':onPlayerReady,'onStateChange':onPlayerStateChange}});}function onPlayerReady(a){a.target.playVideo();}function onPlayerStateChange(event){if (event.data == YT.PlayerState.ENDED){playNext()}};function playNext() {ytplayer.loadVideoById(playlist.shift());}</script><iframe id='playerId' type='text/html' width=\"100%\" height=\"100%\" src='http://www.youtube.com/embed/\(VideoId)?enablejsapi=1&rel=0&playsinline=1&autoplay=1' frameborder='0'/></body></html>"
    ///println(script)
                  ViewWebView.mediaPlaybackRequiresUserAction = false

    ViewWebView.allowsInlineMediaPlayback = true
    ViewWebView.loadHTMLString(script, baseURL: nil)
}


func tableView(tableView:UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
    return 100
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    if yVideo.totalItems > 0{
        return yVideo.totalItems
    }else{
        return fVideo.totalItems
    }

}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
    if indexPath.section == 0{
        if indexPath.row < yVideo.totalItems{
            let cell = tableView.dequeueReusableCellWithIdentifier("VideoPlayerCell") as! PlayerTableViewCell
            cell.playerTitle.text = yVideo.youVideoTitles[indexPath.row]                              

            var ImageUrl: NSURL? = NSURL(string: yVideo.youVideoThumbnails[indexPath.row])
            if let unwrappedImageUrl = ImageUrl{
                var ImageData:NSData! = NSData(contentsOfURL: unwrappedImageUrl, options: NSDataReadingOptions.DataReadingMappedIfSafe, error: nil)

                if let unwrappedImageData = ImageData{
                    var image: UIImage! = UIImage(data: unwrappedImageData)

                    if let unwrappedImage = image{

                        var cellthumbnail = UIImageView(image: unwrappedImage)

                        cell.playerThumb.addSubview(cellthumbnail)

                    }
                }


            }


        return cell
        }
        else{
            let cell = tableView.dequeueReusableCellWithIdentifier("VideoPlayerCell") as! PlayerTableViewCell


            cell.playerTitle.text = fVideo.youVideoTitles[indexPath.row]



            var ImageUrl: NSURL? = NSURL(string: fVideo.youVideoThumbnails[indexPath.row])
            if let unwrappedImageUrl = ImageUrl{
                var ImageData:NSData! = NSData(contentsOfURL: unwrappedImageUrl, options: NSDataReadingOptions.DataReadingMappedIfSafe, error: nil)

                if let unwrappedImageData = ImageData{
                    var image: UIImage! = UIImage(data: unwrappedImageData)

                    if let unwrappedImage = image{

                        var cellthumbnail = UIImageView(image: unwrappedImage)

                        cell.playerThumb.addSubview(cellthumbnail)

                    }
                }


            }

            return cell
        }
    }
    return UITableViewCell()
}



func tableView(table: UITableView, didSelectRowAtIndexPath indexPath:NSIndexPath) {

    self.performSegueWithIdentifier("GoNextView", sender: indexPath);

}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    println(segue.identifier)
    if segue.identifier == "GoNextView"{

        let DestViewController : SeCondVideoViewController = segue.destinationViewController as! SeCondVideoViewController

        let rowsss = self.playerTableView.indexPathForSelectedRow()
        let row = rowsss!

        if yVideo.youVideoIds.count != 0 {
            let serch = searchItem
            DestViewController.searchItem = serch
            let V:AnyObject = yVideo.youVideoIds[row.row]
            DestViewController.VideoItem = V
        }else{
            let serch = "noSearch"
            DestViewController.searchItem = serch
            let V:AnyObject = fVideo.youVideoIds[row.row]
            DestViewController.VideoItem = V
        }

    }
}


func viewWillEnterForeground(notification: NSNotification?) {
    println("foreground")
}

// AppDelegate -> applicationDidEnterBackgroundの通知
func viewDidEnterBackground(notification: NSNotification?) {
    bkgVideoId.load()
    println(bkgVideoId.bVideo[0])
    getHTMLs(bkgVideoId.bVideo[0])
    println("background")
}

/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/
}

0 个答案:

没有答案