URL 在 Swift 3 中始终为零 [英] URL is always nil in Swift 3

查看:17
本文介绍了URL 在 Swift 3 中始终为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构体,用于调用 iTunes API.但是当我运行它时 myURL 变量永远不会被设置,它总是 nil.不知道我做错了什么:

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
    }
}

这是字符串:

"https://itunes.apple.com/search?media=music&entity=song&term=The Chain"

推荐答案

你得到 nil 因为 URL 包含一个空格.您需要先对字符串进行编码,然后再将其转换为 URL.

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()
}

网址将是:

https://itunes.apple.com/search?media=music&entity=song&term=The%20Chain

这篇关于URL 在 Swift 3 中始终为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆