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

时间:2015-10-01 07:58:17

标签: 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);
    }
}

涉及此项目的图书馆。

1 个答案:

答案 0 :(得分:1)

您应该使用Base64初始化程序解码NSData字符串:

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