2015-07-22 23 views
6

tôi có mã nàyCố gắng sử dụng NSJSONSerialization.JSONObjectWithData trên Swift 2

let path : String = "http://apple.com" 
let lookupURL : NSURL = NSURL(string:path)! 
let session = NSURLSession.sharedSession() 

let task = session.dataTaskWithURL(lookupURL, completionHandler: {(data, reponse, error) in 

    let jsonResults : AnyObject 

    do { 
    jsonResults = try NSJSONSerialization.JSONObjectWithData(data!, options: []) 
    // success ... 
    } catch let error as NSError { 
    // failure 
    print("Fetch failed: \(error.localizedDescription)") 
    } 

// do something 

}) 

task.resume() 

nhưng nó là không trên dòng let task với lỗi:

invalid conversion from throwing function of type (__.__.__) throws to non throwing function type (NSData?, NSURLResponse?, NSError?) -> Void

gì là sai? Đây là Xcode 7 beta 4, iOS 9 và Swift 2.


chỉnh sửa:

vấn đề dường như là với những dòng

do { 
    jsonResults = try NSJSONSerialization.JSONObjectWithData(data!, options: []) 
    // success ... 
    } catch let error as NSError { 
    // failure 
    print("Fetch failed: \(error.localizedDescription)") 
    } 

tôi loại bỏ những dòng này và lỗi let task biến mất .

Trả lời

9

Dường như vấn đề nằm trong tuyên bố catch. Mã sau sẽ không tạo ra lỗi bạn đã mô tả.

do { 
    jsonResults = try NSJSONSerialization.JSONObjectWithData(data!, options: []) 
    // success ... 
} catch { 
    // failure 
    print("Fetch failed: \((error as NSError).localizedDescription)") 
} 

Tôi nhận thấy rằng mã bạn đã cung cấp được cho là chính xác, vì vậy bạn nên cân nhắc việc gửi một lỗi với Apple về việc này.

2

Apple đã thay thế NSError bằng ErrorType trong Swift 2 Chỉnh sửa: trong nhiều thư viện.

Vì vậy, hãy thay thế việc sử dụng NSError của riêng bạn bằng ErrorType.

Sửa

Apple đã làm điều này cho một số thư viện trong Swift 2, nhưng không phải tất cả được nêu ra. Vì vậy, bạn vẫn phải suy nghĩ nơi sử dụng NSError và nơi để sử dụng ErrorType.

2

Bạn cũng có thể giả định không có lỗi với:

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

Look, Ma ... không có tay!

0

Đối nhanh chóng 3:

do { 
    jsonResults = try JSONSerialization.JSONObject(with: data!, options: []) 
// success ... 
} catch {// failure 
    print("Fetch failed: \((error as NSError).localizedDescription)") 
} 
Các vấn đề liên quan