2016-08-24 4 views
0

안녕하세요 NSJSONSerialization이 API에서 JSON을 읽고 문제에 봉착를 풀기 동안 예기치 않게 전무을 발견JSONObjectWithData 오류 : 옵션 값

코드 :

func json() { 
    let urlStr = "https://apis.daum.net/contents/movie?=\etc\(keyword)&output=json" 
    let urlStr2: String! = urlStr.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet()) 
    let url = NSURL(string: urlStr2) 
    let data = NSData(contentsOfURL: url!) 

    do { 

     let ret = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0)) as! NSDictionary 

     let channel = ret["channel"] as? NSDictionary 
     let item = channel!["item"] as! NSArray 

     for element in item { 
     let newMovie = Movie_var() 

     // etc 

     movieList.append(newMovie) 
    } 


    catch { 
    } 
} 

그리고이 오류

let ret = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0)) as! NSDictionary 
무엇입니까

치명적인 오류 : 예기치 않게 찾지 못함 없음 선택 값

어떻게 고칠 수 있습니까?

+0

확인이 제대로 코드를 포맷하십시오. 덕분에 –

답변

0

contentsOfURL NSData의 초기화 프로그램의 반환 유형은 선택적 NSData입니다. contentsOfURL 초기화 방법 (선택 사양)를 반환하기 때문에

let data = NSData(contentsOfURL: url!) //This returns optional NSData 

먼저 당신은 포장을 푸는 데 필요한 옵션 아래 그림과 같이이 nil이 아닌 경우 데이터를 사용하여 다음을하자 경우 를 사용하여.

if let data = NSData(contentsOfURL: url!) { //Also it is advised to check for whether you can type cast it to NSDictionary using as?. If you use as! to force type cast and if the compiler isn't able to type cast it to NSDictionary it will give runtime error. if let ret = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)) as? NSDictionary { //Do whatever you want to do with the ret } } 

그러나 코드의 경우

는 확인하지 않을 니펫을 당신이 contentsOfURL에서 얻을 데이터 전무인지 아닌지 여부. 당신은 강제로 데이터의 래핑을 해제하고 데이터를 nil로 설정하면 래핑 해제가 실패하고
을 래핑 해제하는 동안 이 예기치 않게 발견됩니다.

희망이 도움이됩니다. `data` 인`nil`하고, 다음 시간

+0

! :) 나는 당신의 도움으로 해결하려고 노력할 것입니다! –