2017-09-25 1 views
0

저는 iTunes API를 호출하기 위해 사용하는 구조체가 있습니다. 하지만 언제든지 나는 그것을 실행하면 myURL 변수가 결코 설정되지 않고, 항상 nil입니다. 내가 잘못하고있는 중이 야 확실하지 무엇을 :URL은 Swift 3에서는 항상 nil입니다.

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

다음은 문자열의 다음 URL에 공백이 포함되어 있기 때문에

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

포스트 문자열해서 getJSON –

+0

https://itunes.apple.com/search?media=music&entity=song&term=The 체인에 전달 기쁘지 – PruitIgoe

답변

5

멋져요는 nil를 받고. 문자열을 먼저 인코딩 한 다음 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 
관련 문제