Reputation: 1
the code here goes to the credit of Jameson Quave.
URL: www.jamesonquave.com/blog/developing-ios-apps-using-swift-tutorial-part-2/
I have attempted to edit it to work with Swift 3. The issue I am having is the error message for this line:
if let escapedSearchTerm = itunesSearchTerm.addingPercentEncoding(withAllowedCharacters: .urlquery)
(it states .utf8
in the code)
I am unsure as to what I need to place in the .urlquery
section
The error code I get is the title. I have tried to google for answers and found String.Encoding.utf8
which also did not work. The original code had 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.
}
}
Upvotes: 0
Views: 679
Reputation: 78865
You'll want to use .urlQueryAllowed
:
escapedSearchTerm = itunesSearchTerm.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
The withAllowedCharacters expects a character set that defines all the characters that do not need escaping. It's not related to the text encoding (such as UTF-8).
Upvotes: 1