ios - 大多数时候 HTML 不会第一次加载

标签 ios iphone xcode swift

我有一个用 Swift 制作的应用程序,为了好玩,而且因为我是初学者。基本上,它的作用是您可以输入艺术家姓名和歌曲名称,它会根据您输入的艺术家和歌曲名称从 AZLyrics.com 获取歌词。由于某种原因,大多数时候,当我第一次尝试加载歌词时,当我打开应用程序时,它不会加载(它会加载第二次、第三次、第四次等)。这是我的代码,有人可以告诉我如何解决这个问题吗?

第一个 View Controller

import UIKit

var lyricsWithQuotes = ""
var urlError = false

class ViewController: UIViewController, UITextFieldDelegate {

@IBOutlet var songName: UITextField!
@IBOutlet var artistName: UITextField!

@IBAction func search(sender: AnyObject) {
    var url = NSURL(string: "http://www.azlyrics.com/lyrics/" + artistName.text.stringByReplacingOccurrencesOfString(" ", withString: "").stringByReplacingOccurrencesOfString("'", withString: "").stringByReplacingOccurrencesOfString(",", withString: "").stringByReplacingOccurrencesOfString(".", withString: "").lowercaseString + "/" + songName.text.stringByReplacingOccurrencesOfString(" ", withString: "").stringByReplacingOccurrencesOfString("'", withString: "").stringByReplacingOccurrencesOfString(",", withString: "").stringByReplacingOccurrencesOfString(".", withString: "").lowercaseString  + ".html")

    if url != nil {

        let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in

            if error == nil {

                var urlContent = NSString(data: data, encoding: NSUTF8StringEncoding) as NSString!

                var urlContentArray = urlContent.componentsSeparatedByString("<!-- Usage of azlyrics.com content by any third-party lyrics provider is prohibited by our licensing agreement. Sorry about that. -->")

                if urlContent.containsString("It's a place where all searches end!") {

                    urlError = true

                } else {

                    var lyricsArray = urlContentArray[1].componentsSeparatedByString("<br><br>")

                    var lyrics = lyricsArray[0] as! String

                    var lyricsWithoutBR = lyrics.stringByReplacingOccurrencesOfString("<br>", withString: "")

                    var lyricsWithoutSlashDiv = lyricsWithoutBR.stringByReplacingOccurrencesOfString("</div>", withString: "")

                    var lyricsWithoutI = lyricsWithoutSlashDiv.stringByReplacingOccurrencesOfString("<i>", withString: "")

                    var lyricsWithoutSlashI = lyricsWithoutI.stringByReplacingOccurrencesOfString("</i>", withString: "")

                    lyricsWithQuotes = lyricsWithoutSlashI.stringByReplacingOccurrencesOfString("&quot;", withString: "\"")

                }

            } else {

                urlError = true

            }

        })

        task.resume()

    } else {

        urlError = true

    }


}

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    view.endEditing(true)
}

func textFieldShouldReturn(textField: UITextField) -> Bool {

    textField.resignFirstResponder()

    return true
}

override func viewDidLoad() {
    super.viewDidLoad()

    artistName.delegate = self

    songName.delegate = self

}

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


}

第二个 View Controller

import UIKit

var lyricsComplete = ""

class ViewController2: UIViewController {

@IBOutlet var lyricsDisplay: UITextView!

override func viewDidAppear(animated: Bool) {

    if urlError == true {

        urlError = false
        lyricsDisplay.text = "Couldn't find that song!"

    } else {

        lyricsComplete = lyricsWithQuotes
        lyricsDisplay.text = lyricsComplete

    }
}

override func viewDidLoad() {
    super.viewDidLoad()

}

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


}

最佳答案

在你的 NSURLSession 完成之后 - 基本上是这一行:

lyricsWithQuotes = lyricsWithoutSlashI.stringByReplacingOccurrencesOfString("&quot;", withString: "\"")

您有两个选择:

选项一 - 以编程方式启动 View :

let storyboard = UIStoryboard(name: "STORYBOARD NAME HERE", bundle: nil)
let newVC = storyboard.instantiateViewControllerWithIdentifier("VIEW CONTROLLER IDENTIFIER HERE") as! ViewController2
newVC.lyricsComplete = lyricsWithQuotes

如果您有导航 Controller :

self.navigationController?.pushViewController(newVC, animated: true)

如果您没有导航 Controller :

self.showViewController(newVC, sender: self)

选项 2 - 触发 Segue:

performSegueWithIdentifier("SEGUE NAME HERE", sender: nil)

然后拦截Segue

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.

    if(segue.identifier == "SEGUE NAME HERE"){
        let newVC = segue.destinationViewController as! ViewController2
        newVC.lyricsComplete = lyricsWithQuotes
    }
}

如果您使用选项 2,请确保 Segue 位于 View Controller 之间并且未附加到您的按钮:

像这样:

Segue Correct

不是这样的:

Segue Incorrect

关于ios - 大多数时候 HTML 不会第一次加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31981601/

相关文章:

ios - Adobe Creative SDK iOS : Framework CreativeSDKImage requires framework CreativeSDKFoundation but framework CreativeSDKFoundation is not present

ios - 成功谷歌登录后应用程序在 IOS 中崩溃( Objective-C )

iphone - @autoreleasepool 做什么?

ios - 我的项目中的 Xcode 6 无效权利

iphone - 自定义 UI View 更改框架大小

c++ - 使用 Makefile 构建时,索引和语法突出显示在 Xcode 中不起作用

objective-c - 模态视图 Controller 转换

ios - 在 ios 7 中发送电子邮件而不显示电子邮件编辑器 View

cocoa-touch - 扩展界面生成器中的属性检查器

ios - 如何在 Swift 的 UIButton 中删除图像和写入文本?