ios - 无法弄清楚如何在 Swift 中使用 NSURLSession 将 jsonData 加载到 NSDictionary

标签 ios json swift rest nsurlsession

大家好。首先,我想告诉您,总体而言,我在编程方面还很陌生。因此,如果我没有任何意义,我想先道歉。我已经完成了 iOS Swift 的训练营,但不包括 Rest 或解析 JSON。我现在正在努力自学做我能找到的所有教程。我知道有 Alamofire 使它更容易,但我想先学习如何使用 NSURLSession 来完成它。我发现了一个用旧版本的 Swift 编写的教程,现在我已经被困了好几天了。我已经尝试了在这里和在 Google 上可以找到的所有选项。但我仍然不明白我做错了什么。这是我的代码;在它下面我描述了我认为问题发生的地方。 预先感谢您的帮助。

import Foundation
import UIKit

class FlickrHelper: NSObject {

class func UrlForSearchString(searchString: String) -> String {
    let apiKey:String = "733e5b6f446812afdec3c021454dd9bb"
    let search:String = searchString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
    return "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=\(apiKey)&text=\(search)&per_page=20&format=json&njsoncallback=1"

}
class func UrlForFlickrPhoto(photo:FlickrPhoto, size:String) -> String {
    var _size = size
    if _size.isEmpty {
        _size = "m"
    }
    return "http://farm.\(photo.farm).staticflickr.com/\(photo.photoID)_\(photo.secret)_\(_size).jpg"
}

func searchFlickrForString(searchStr:String, completion:(searchString:String!, flickrPhotos:NSMutableArray!, error:NSError!) -> ()) {

    let searchUrl:String = FlickrHelper.UrlForSearchString(searchStr)
    let queue:dispatch_queue_t = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

    dispatch_async(queue, {

        var error:NSError?

        let searchResultString:String! = try! String(contentsOfURL: NSURL(string: searchUrl)!, encoding: NSUTF8StringEncoding)

        if error != nil {
            completion(searchString: searchStr, flickrPhotos: nil, error: error)
        } else {
            // Parse json response.

            let jsonData:NSData! = searchResultString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)

            let resultDict = try? NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as! [String:AnyObject] as NSDictionary

            let status:String = resultDict?.objectForKey("stat") as! String

            if status == "fail" {
                let stError:NSError? = NSError(domain: "FlickrSearch", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey:(resultDict?.objectForKey("message"))!])

                completion(searchString: searchStr, flickrPhotos: nil, error: stError)
            } else {
                let resultArray:NSArray = (resultDict?.objectForKey("photos")?.objectForKey("photo"))! as! NSArray

                let flickrPhotos:NSMutableArray = NSMutableArray()

                for photoObject in resultArray {
                    let photoDict:NSDictionary = photoObject as! NSDictionary

                    var flickrPhoto:FlickrPhoto = FlickrPhoto()
                    flickrPhoto.farm = photoDict.objectForKey("farm") as! Int
                    flickrPhoto.server = photoDict.objectForKey("server") as! String
                    flickrPhoto.secret = photoDict.objectForKey("secret") as! String
                    flickrPhoto.photoID = photoDict.objectForKey("id") as! String

                    let searchURL:String = FlickrHelper.UrlForFlickrPhoto(flickrPhoto, size: "m")
                    do {
                    let imageData:NSData = try NSData(contentsOfURL: NSURL(string: searchURL)!, options: NSDataReadingOptions())

                        let image:UIImage = UIImage(data:imageData)!

                        flickrPhoto.thumbnail = image

                        flickrPhotos.addObject(flickrPhoto)

                    } catch {
                        print(error)
                    }

                    completion(searchString: searchStr, flickrPhotos: flickrPhotos, error: nil)

                }
            }
        }
    })
  }
}

我收到 jsonData 但它没有将它分配给我的 resultDict。我的 resultDict 是零。我的项目崩溃的那一行是:

 let status:String = resultDict?.objectForKey("stat") as! String

但我猜问题出在这一行:

let resultDict = try? NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as! [String:AnyObject] as NSDictionary

最佳答案

试试这个。

不要将空数组传递给 NSJSONSerialization.JSONObjectWithData,而是使用片段类型允许,如下所示:

let resultDict = try? NSJSONSerialization.JSONObjectWithData(jsonData, NSJSONReadingOptions.AllowFragments)

这可能会解决问题。否则尝试其他一些选项。


另一种方法可能是这样。

            let json = try! NSJSONSerialization.JSONObjectWithData(json!, options: .AllowFragments)
            print("=====")
            if let item = json.objectForKey("prices") as! NSArray? {
                self.uberPriceField.text = item[0].objectForKey("estimate") as? String
            }

我在自己的代码中使用了它,因为返回的 JSON 实际上只是顶层的一个数组。也许它对你也有用。

关于ios - 无法弄清楚如何在 Swift 中使用 NSURLSession 将 jsonData 加载到 NSDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37375574/

相关文章:

SwiftMessages Exec Bad Access 使用 SwiftMessages.defaultConfig

ios - 检测打开应用程序的 UILocalNotification

javascript - 无法从 json 记录集中打印表中的变量

python - 如何在Python中将提取的文本从PDF转换为JSON或XML格式?

java - Jersey 返回一个 JSONObject

ios - Swift 闭包内存使用

ios - 添加编程 View 而不是 Storyboard 后出现意外的 nil

iphone - Apple App Store 上的应用程序提交

iphone - 如何从 NSDictionaries 的 NSArray 读取值

iphone - 令人困惑的 iPhone 应用程序中的双重免费错误消息/内存泄漏