ios - Swift - JSON 写入中的顶级类型无效

标签 ios json swift alamofire swifty-json

我的项目使用 Xcode 6.4 和 swift 1.2。问题是我无法解析我的 base64 pdf 并加载到 webview 中。我在尝试解析 pdf 时收到此错误消息。

错误信息

2015-10-01 15:54:29.105 XXXXX[13605:417122] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010ebfac65 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x000000010e4d7bb7 objc_exception_throw + 45
    2   CoreFoundation                      0x000000010ebfab9d +[NSException raise:format:] + 205
    3   Foundation                          0x000000010e17471a +[NSJSONSerialization dataWithJSONObject:options:error:] + 264
    4   SwiftyJSON                          0x000000010dfb8327 _TFV10SwiftyJSON4JSON7rawDatafS0_FT7optionsVSC20NSJSONWritingOptions5errorGVSs33AutoreleasingUnsafeMutablePointerGSqCSo7NSError___GSqCSo6NSData_ + 183
    5   XXXXX                                0x000000010d69705c _TFFC4KPMG27VeritatDetailViewController11viewDidLoadFS0_FT_T_U_FTCSo12NSURLRequestGSqCSo17NSHTTPURLResponse_GSqPSs9AnyObject__GSqCSo7NSError__T_ + 796
    6   Alamofire                           0x000000010dc4af4e _TFFC9Alamofire7Request12responseJSONFDS0_FT7optionsVSC20NSJSONReadingOptions17completionHandlerFTCSo12NSURLRequestGSqCSo17NSHTTPURLResponse_GSqPSs9AnyObject__GSqCSo7NSError__T__DS0_U_FTS2_GSqS3__GSqPS4___GSqS5___T_ + 126
    7   Alamofire                           0x000000010dc46c53 _TFFFC9Alamofire7Request8responseFDS0_FT5queueGSqCSo8NSObject_10serializerFTCSo12NSURLRequestGSqCSo17NSHTTPURLResponse_GSqCSo6NSData__TGSqPSs9AnyObject__GSqCSo7NSError__17completionHandlerFTS2_GSqS3__GSqPS5___GSqS6___T__DS0_U_FT_T_U_FT_T_ + 403
    8   Alamofire                           0x000000010dc19527 _TTRXFo__dT__XFdCb__dT__ + 39
    9   libdispatch.dylib                   0x0000000111a7a186 _dispatch_call_block_and_release + 12
    10  libdispatch.dylib                   0x0000000111a99614 _dispatch_client_callout + 8
    11  libdispatch.dylib                   0x0000000111a81a1c _dispatch_main_queue_callback_4CF + 1664
    12  CoreFoundation                      0x000000010eb621f9 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
    13  CoreFoundation                      0x000000010eb23dcb __CFRunLoopRun + 2043
    14  CoreFoundation                      0x000000010eb23366 CFRunLoopRunSpecific + 470
    15  GraphicsServices                    0x0000000111ec5a3e GSEventRunModal + 161
    16  UIKit                               0x000000010f5fb8c0 UIApplicationMain + 1282
    17  XXXXX                                0x000000010d671887 main + 135
    18  libdyld.dylib                       0x0000000111acd145 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

ViewController.swift

import UIKit
import Alamofire
import SwiftyJSON

class ViewController: UIViewController {

    var datas: [JSON] = []
    @IBOutlet var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        Alamofire.request(.POST , "http://192.168.1.189/xxxxx/pdf.asmx/WSpdf", parameters:nil)
            .responseJSON { request, response, json, error in
                //println(json)
                if json != nil {

                    var jsonObj = JSON(json!)
                    let jsonData:NSData = jsonObj[0]["Data"].rawData()!
                    self.displayPdf(jsonData)
                }
        }
    }

    func displayPdf(pdfContent: NSData){
        var paths: NSArray = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask, true)
        var documentsDirectory: NSString = paths.objectAtIndex(0) as! NSString

        var finalPath: NSString = documentsDirectory.stringByAppendingPathComponent("myPdf.pdf")

        var url: NSURL = NSURL.fileURLWithPath(finalPath as String)!
        pdfContent.writeToURL(url, atomically: true)

        let requestObj = NSURLRequest(URL: url);
        webView.loadRequest(requestObj);
    }
}

本项目涉及的库。

最佳答案

你应该使用 NSData 初始化器解码 Base64 字符串:

if let s = jsonObj[0]["Data"].string {
    self.displayPdf(NSData(base64EncodedString: s, options: NSDataBase64DecodingOptions(rawValue: 0)))
}

关于ios - Swift - JSON 写入中的顶级类型无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32882325/

相关文章:

Swift UI - 如何从外部访问 @State 变量?

ios - 提示计算器 - 在展开可选值时意外发现 nil

ios - 从未在 viewForSupplementaryElementOfKind 中检测到 UICollectionElementKindSectionFooter

iphone - 在 View 加载时加载搜索栏单击

javascript - 遍历 JSON - 特殊方式

json - 与颜色相关的 flutter 图像

swift - CLLocation distanceFromLocation(在 Swift 中?)

ios - 如何在苹果 Apple Watch UI 中叠加项目

javascript - 在服务器目录中查找最新的 JSON 文件

ios - 如何使用 Swift 以编程方式将 UIButton 中的文本左对齐,图像右对齐?