无法将类型“ [String]”的值转换为预期的参数类型“([[AnyObject])->无效”

时间:2018-11-20 16:51:26

标签: ios swift

我有一个如下的项目代码,希望它可以从func getUrls()获取url,但是Xcode返回错误消息,如标题所说。

我进行了搜索,并尝试了一些解决方案来修复它,但所有方法均无效。我应该用另一种方式编写它,还是仅解决此错误?是不是对arrUrls的声明是错误的,还是需要进行更正的地方?

p.s。如果您通过评论回答我,请记住教我如何为您的回答打上“答题标记”。:)谢谢。

var arrUrls = [String]()

@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
    super.viewDidLoad()


getUrls(url: url, completion: arrUrls) // Error Message: Cannot convert value of type '[String]' to expected argument type '([AnyObject]) -> Void'

...do something with array 'arrUrl'....but can't, because of the bug!

}



func getUrls(url : URL  ,completion: @escaping (([AnyObject]) -> Void)) {

    let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) -> Void in
        do {
            if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as? [String : AnyObject] {

                if let subjects = jsonResult["subjects"] as? [AnyObject]? {

                    for subject in subjects! {
                        if let content = subject["content"] as? [String : AnyObject] {

                            let s = String(describing: content["url"]!)
                            arrUrls.append(s)
                        }
                    }
                }
            }
            completion(arrUrls as [AnyObject])
        }catch {
            print("json error: \(error)")
        }
    })
    task.resume()
}

1 个答案:

答案 0 :(得分:0)

您需要这样打电话

getUrls(url: url) { (arr) in


}

如果您在函数内部编辑数组,则无需返回完成值

func getUrls(url : URL  ,completion: @escaping (() -> Void)) 

使用

getUrls(url: url) {  

  // refresh ui here

 DispatchQueue.main.async {
   if firstItem = self.arrUrls.first , let url = URL(string:firstItem) {
      webView.load(URLRequest(url: url))
   }
 }

将代码更改为此

func getUrls(url : URL  ,completion: @escaping (() -> Void)) {

    let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) -> Void in

        guard let data = data else { return }

        do {
            if let jsonResult = try JSONSerialization.jsonObject(with: data) as? [String : Any] {

                if let subjects = jsonResult["subjects"] as? [[String:Any]] {

                    for subject in subjects {

                        if let content = subject["content"] as? [String : Any] {

                           if let s = content["url"] as? String
                           {
                              self.arrUrls.append(s)
                           }
                        }
                    }

                    completion()

                }
            }

        }catch {

            completion()
        }
    })
    task.resume()
}