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

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

问题描述

我有一个用于调用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"

推荐答案

由于URL包含空格,您将得到nil.您需要先对字符串进行编码,然后再将其转换为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()
}

URL将是:

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

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

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