I have a struct that I am using to call out to the iTunes API. But when ever I run it myURL variable is never getting set, it's always nil. Not sure what I am doing wrong:
let myDefaultSession = URLSession(configuration: .default)
var myURL: URL?
var myDataTask: URLSessionTask?
struct APIManager {
func getJSON(strURL: String) {
myURL = URL(string: strURL)
var dictReturn: Dictionary<String, Any> = [:]
//cancel data task if it is running
myDataTask?.cancel()
print(myURL!) //<----Always nil
}
}
Here's the string:
"https://itunes.apple.com/search?media=music&entity=song&term=The Chain"
You´re getting nil because the URL contains a space. You need to encode the string first and then convert it to an URL.
func getJSON(strURL: String) {
if let encoded = strURL.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed),
let myURL = URL(string: encoded) {
print(myURL)
}
var dictReturn:Dictionary<String, Any> = [:]
//cancel data task if it is running
myDataTask?.cancel()
}
URL will be:
https://itunes.apple.com/search?media=music&entity=song&term=The%20Chain
Related
I'm totally new with swift, it's my first iOs app
I would like to retrieve a value from an http POST response
struct represCode: Codable{
var CODE: String?
}
var table = [represCode]()
func httpPost(completion: #escaping (_ json: Any?)->()) {
let json: [String: Any] = ["login": usernameText.text!.uppercased(),
"pass": mdpText.text!]
let urlPath = url.chaine + "login.php"
let jsonData = try? JSONSerialization.data(withJSONObject: json)
let url = URL(string: urlPath)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
// insert json data to the request
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
do {
self.table = try JSONDecoder().decode([represCode].self, from: data)
print(self.table)
self.dl = true
}catch _ {
print ("JSON Error")
}
completion(json)
}
task.resume()
}
When I "print(self.table)" I get this
[Mobois.LoginViewController.represCode(CODE: Optional("AG"))]
And I would like to store the "AG" in a specific var (ex: var represCode: String?)
I tried many solutions that I found here but most of time I get errors like "Cannot assign value of type '[LoginViewController.represCode]' to type 'String'"
There are two serious mistakes.
The root object is an array (represented by the [] in [represCode].self)
The value AG is the value for key CODE
First of all to conform to the naming convention declare the struct this way
struct RepresCode: Decodable {
let code: String
private enum CodingKeys: String, CodingKey { case code = "CODE" }
}
and
var table = [RepresCode]()
..
JSONDecoder().decode([RepresCode].self ...
You can access the value by getting the value for property code of the first item in the array
let represCode = table.first?.code ?? "unknown code"
I'm getting this error on line var delegate = WeatherManagerDelegate()
import Foundation
protocol WeatherManagerDelegate {
func didUpdateWeather(weather:WeatherModel)
}
struct WeatherManager {
let weatherURL = "https://api.openweathermap.org/data/2.5/weather?&appid=d73ab8784f3b294976fc6189b3e6eba2&units=metric"
var delegate = WeatherManagerDelegate()
func fetchWeather(cityName: String) {
let urlString = "\(weatherURL)&q=\(cityName)"
performRequest(urlString: urlString)
}
func performRequest(urlString: String)
{
//Create URL
if let url = URL(string: urlString){
//Create a URL Session.
let session = URLSession(configuration: .default)
//Give session a task
let task = session.dataTask(with: url) { (data, response, error) in
if error != nil{ //on selecting url 2nd option the seletors you get select from data onwards to error and press enter and it will be set to closure format.
print(error!)
return
}
if let safeData = data {
/* let dataString = String(data: safeData, encoding: .utf8)
print(dataString!)*/
if let weather = parseJSON(weatherData: safeData) {
self.delegate.didUpdateWeather(weather:weather)
}
}
}
//Start task
task.resume()
}
}
func parseJSON(weatherData: Data) ->WeatherModel? {
let decoder = JSONDecoder()
do{
let decodeData = try decoder.decode(WeatherData.self, from: weatherData)
let name = decodeData.name
let temp = decodeData.main.temp
print(decodeData.main.temp_max)
print(decodeData.main.temp_min)
print(decodeData.sys.country)
print(decodeData.weather[0].description)
let id = decodeData.weather[0].id
let weather = WeatherModel(conditionId: id, cityName: name, temperature: temp)
print(weather.conditionName)
print(weather.temperatureString)
}
catch{
print(error)
return nil
}
}
}
and when I'm trying to make it an optional
var delegate = WeatherManagerDelegate?()
I'm getting this error
No exact matches in call to initializer
Replace
var delegate = WeatherManagerDelegate()
with
weak var delegate: WeatherManagerDelegate?
and update the calls to read self.delegate?.didUpdateWeather()
WeatherManager should not be responsible for creating its own delegate, that is something that should come from wherever it is begin used.
The weak attribute is almost always necessary when using delegates to avoid retain cycles.
Since weak can only be applied to class objects, you also need to indicate that in the protocol definition:
protocol WeatherManagerDelegate: AnyObject { ... }
I can't find a solution for my programming issue. I want to create a function which will access a dictionary (data is coming from the internet) an I need the following code very often:
if let job_dict = json["data"] as? [String:Any] {
It would be great to be more flexible and to change the ["data"] part to a variable or something like that:
func get_JSON(Link: String, Value: String) -> [Double] {
let url = Link
let request = URLRequest(url: URL(string: url)!)
let myUrl = URL(string: basePath)!
var ValuestoReturn = [Double]()
let task = URLSession.shared.dataTask(with: myUrl) { (data, response, error) in
if let data = data {
do {
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] {
print(Value.description)
if let job_dict = json[Value.description] as? [String:Any] {
print(job_dict)
}
}
} catch {
}
}
}
task.resume()
json[Value.description] is always wrong and the json["data"] thing is always true.
Don't use Value.Description use just Value
print(Value)
if let job_dict = json[Value] as? [String:Any] {...}
P.D: Don't use "Value" for a variable's name. The first letter in uppercase is for types. You can use value instead.
I'm new here, so please bear with me. I have a Master-Detail app, and in the DetailViewController.swift file, here's the configureView func where it calls a web view to open a web page.
It's complaining on the let request = URLRequest(url:url) line because url variable is defined as a string. I've tried everything but it won't work.
By the way, MasterViewController.MyVariables.urlString is an array of strings.
func configureView() {
// Update the user interface for the detail item.
if let detail: AnyObject = detailItem {
if let myWebview = webView {
let url = MasterViewController.MyVariables.urlString
let request = URLRequest(url: url)
myWebview.scalesPageToFit = true
myWebview.loadRequest(request)
}
}
}
You can either pass an URL object or create an URL object from the string that you´re passing. Anyhow you need to convert your string into an URL.
if let url = URL(string: MasterViewController.MyVariables.urlString) {
// use url in here
}
Update:
Use this for your example:
if let url = URL(string: MasterViewController.MyVariables.urlString) {
// use url in here
let request = URLRequest(url: url)
}
Update 2:
You have your Struct which is an array of strings. Then you need to do this to get the value you want:
struct MyVariables {
static var urlString: [String]? = ["something"]
}
if let str = MyVariables.urlString?.first, let url = URL(string: str) {
// use url in here
let request = URLRequest(url: url)
print(url)
}
Right now I´m using MyVariables.urlString?.first, in the future if you want another index then you need to get that instead.
This is what I did to make it work:
let stringRepresentation = MasterViewController.MyVariables.urlString?.joined(separator:"")
print ("urlString", MasterViewController.MyVariables.urlString)
print ("sR",stringRepresentation)
let url = NSURL(string: stringRepresentation as! String)
let request = URLRequest(url: url! as URL)
myWebview.scalesPageToFit = true
myWebview.loadRequest(request)
Let's say I have the following class definition:
class Request {
let url: NSURL?
init?(url: String) {
guard let self.url = NSURL(string: url) else {
self.url = nil
return nil
}
}
}
The guard statement doesn't work so I'm having to do the following:
let url: NSURL?
init?(url: String) {
guard let _ = NSURL(string: url) else {
self.url = nil
return nil
}
self.url = NSURL(string: url)!
}
Which feels quite long - is there another, simpler way to achieve what I'm trying to achieve which is to create a failable initialiser whose only property takes a value from NSURL (which returns an optional). The initialiser is to fail and return nil if the NSURL value returns nil.
Your first version could work, you just forgot to give guard a variable name for the unwrapped value (you used self.url instead, that's the mistake):
class Request {
let url: NSURL?
init?(url: String) {
guard let value = NSURL(string: url) else {
self.url = nil
return nil
}
self.url = value
}
}