2017-01-10 88 views
0

这里的代码将归功于Jameson Quave。类型“字符集”没有成员“utf8”

网址:www.jamesonquave.com/blog/developing-ios-apps-using-swift-tutorial-part-2/

我试图编辑与斯威夫特3.我的问题而努力有针对该行的错误消息:

if let escapedSearchTerm = itunesSearchTerm.addingPercentEncoding(withAllowedCharacters: .urlquery) 

(它指出.utf8代码)

我不确定什么,我需要在.urlquery部分放置

我得到的错误代码是标题。我试图谷歌的答案,发现String.Encoding.utf8哪些也没有工作。原始代码有NSUTF8StringEncoding

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 

    @IBOutlet weak var appsViewTable: UITableView! 
    var tableData = [] 

    func searchItunesFor(searchTerm: String) { 
     //The iTunes API wants multiple terms seperated by + symbols, so replace spaces with + signs 
     let itunesSearchTerm = searchTerm.replacingOccurrences(of: " ", with: "+", options: NSString.CompareOptions.caseInsensitive, range: nil) 

     //Now escape anything else that isn't URL-friendly 
     if let escapedSearchTerm = itunesSearchTerm.addingPercentEncoding(withAllowedCharacters: .utf8) { 
      let urlPath = "http://itunes.apple.com/search?term=\(escapedSearchTerm)&media=software" 
      let url = NSURL(string: urlPath) 
      let session = URLSession.shared 
      let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in 
       printIn("Task completed") 
       if(error != nil) { 
        // If there is an error in the web request, print it to the console 
        printIn(error.localizedDescription) 
       } 
       var err: NSError? 
       if let jsonResult = NSJSONSerialization.JSONObjectiveWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary { 
        if(err != nil) { 
         // If there is an error parsing JSON, print it to the console 
         printIn("JSON Error \(err!.localizedDescription)") 
        } 
        if let results: NSArray = jsonResult["results"] as? NSArray { 
         dispatch_async(dispatch_get_main_queue(), { 
          self.tableData = results 
          self.appsTableView!.reloadData() 
         }) 
        } 
       } 
      }) 

     // The task if just an object with all these properties set 
     // In order to actually make the web request, we need to "resume" 
     task.resume() 
     } 
    } 
    override func viewDidLoad() { 
     super.viewDidLoad() 
     // 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. 
    } 
} 
+2

尝试使用'String.Encoding.utf8.rawValue' – Tj3n

回答

1

你要使用.urlQueryAllowed

escapedSearchTerm = itunesSearchTerm.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) 

withAllowedCharacters期望一个字符集,它定义了不需要转义的所有字符。它与文本编码无关(如UTF-8)。

相关问题