我收到错误无法转换字符串类型的值 在此常量下强制键入url。谢谢你提前帮助:)
**let safariVC = SFSafariViewController(url: JobUrl as URL)**
import UIKit
import SafariServices
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
//Indeed API Query as JSON
final let urlString = "http://api.indeed.com/ads/apisearch?publisher=9727336427429597&as_phr=&as_any=&as_not=&as_ttl=&as_cmp=&jt=parttime&st=&salary=&radius=25&l=32304&fromage=any&limit=25&sort=&psf=advsrch=&userip=1.2.3.4&useragent=Mozilla/%2F4.0%28Firefox%29&v=2&format=json"
@IBOutlet weak var tableView: UITableView!
var jobTitleArray = [String]()
var snippetArray = [String]()
var companyArray = [String]()
var cityArray = [String]()
var jobUrlArray = [String]()
// url = URL(string: epsDictionary["link"] as! String)
override func viewDidLoad() {
super.viewDidLoad()
self.downloadJsonWithURL()
// 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
}
//fetch Json
func downloadJsonWithURL() {
let url = NSURL(string: urlString)
URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) ->
Void in
if let JsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
as? NSDictionary {
print(JsonObj!.value(forKey: "results")!)
if let resultsArray = JsonObj!.value(forKey: "results") as? NSArray {
for result in resultsArray {
if let resultDict = result as? NSDictionary {
if let jobTitle = resultDict.value(forKey: "jobtitle") {
self.jobTitleArray.append(jobTitle as! String)
}
if let snippet = resultDict.value(forKey: "snippet") {
self.snippetArray.append(snippet as! String)
}
if let company = resultDict.value(forKey: "company") {
self.companyArray.append(company as! String)
}
if let city = resultDict.value(forKey: "formattedRelativeTime") {
self.cityArray.append(city as! String)
}
if let jobUrl1 = resultDict.value(forKey: "url") {
self.jobUrlArray.append(jobUrl1 as! String)
}
OperationQueue.main.addOperation({
self.tableView.reloadData()
})
}
}
}
}
}).resume()
}
func downloadJsonWithTask() {
let url = NSURL(string: urlString)
var downloadTask = URLRequest(url: (url as? URL)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20)
downloadTask.httpMethod = "Get"
URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) ->
Void in
let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
print(jsonData!)
}).resume()
}
var jobToUrl = URL(string: "http://www.indeed.com/viewjob?jk=5de353a4c580dce0&qd=8FiWEXDXvmdNb_GJC9BAOpLFMiNO7rztIOPtGp_-cISTa1VWcmBigetsBoobMSCXdNyr-z6ge7UiYg2Mx15EH6m1Aj3izkOw87NHJgxznYA&indpubnum=9727336427429597&atk=1bchrhjof5hgga1k")
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
print("USER SELECTED CELL")
let JobUrl = jobUrlArray[indexPath.row]
**let safariVC = SFSafariViewController(url: JobUrl as URL)**
self.present(safariVC, animated: true, completion: nil)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return jobTitleArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
cell.jobTitle.text = jobTitleArray[indexPath.row]
cell.jobSummary.text = snippetArray[indexPath.row]
cell.employerName.text = companyArray[indexPath.row]
cell.cityName.text = cityArray[indexPath.row]
cell.ApplyButton.text = jobUrlArray[indexPath.row]
// let imageUrl = NSURL(string: imageUrlArray[indexPath.row])
// if imageUrl != nil {
// let data = NSData(contentsOf: (imageUrl as? URL)!)
// cell.imageView?.image = UIImage (data: data as! Data)
// }
return cell
}
}
答案 0 :(得分:2)
您无法强制字符串到网址。 Casting简单地说“好吧,这个盒子里的东西。它不是一个字符串,它是一个URL。”如果对象不能像另一个类一样加倍,则转换失败。
您需要使用字符串作为输入创建URL:
let url = URL(string: myString)
答案 1 :(得分:0)
String
和URL
无关,因此无法互相投放。您必须从字符串创建URL(如代码中的另一行)。
let safariVC = SFSafariViewController(url: URL(string: JobUrl)!)
根本不在Swift 3中使用NSURL
。
PS:请注意,如果您使用多个数组作为数据源,downloadJsonWithURL
中的所有可选绑定都毫无意义。如果一个值未通过绑定,则由于超出范围的异常,应用最迟会在cellForRow
中崩溃。
答案 2 :(得分:0)
URL是一个具有不同属性的对象(如absoluteString,path,scheme等,它们是String对象本身),因此您无法将URL转换为String,它们是不同的类型。
使用URL,您可以使用URLSession类来访问远程资源的内容或表示本地路径。查看文档,确保您知道您正在使用的课程。
https://developer.apple.com/reference/foundation/nsurl
在Swift中尝试使用String创建一个URL(通过展开):
if let url = URL(String: jobUrlArray[indexPath.row]) {
let safariVC = SFSafariViewController(url: jobUrl)
}
或在代码中使用url?
但请确保您不要使用明确展开的可选内容,例如:
let safariVC = SFSafariViewController(url: URL(string: JobUrl)!)
您的代码可能会崩溃,但这不安全。