最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】iOS中Alamofire参数解析JSONEncoding出错

iOS crifan 4372浏览 0评论

ios项目中,用到了Alamofire的JSONEncoding去实现参数的json格式化

结果出错:

swift:140] collectionView(_:numberOfItemsInSection:) > curCount=1
2017-10-12 16:11:14.245 [Verbose] [main] [ManageImageTableViewCell.swift:146] collectionView(_:cellForItemAt:) > collectionView=<UICollectionView: 0x7fd4899d3200; frame = (0 0; 375 74.5); clipsToBounds = YES; gestureRecognizers = <NSArray: 0x604000a45f70>; layer = <CALayer: 0x604000839aa0>; contentOffset: {0, 0}; contentSize: {375, 66}; adjustedContentInset: {0, 0, 0, 0}> collection view layout: <UICollectionViewFlowLayout: 0x7fd48e424df0>, indexPath=[0, 0]
2017-10-12 16:11:14.248 [Debug] [main] [ThisVisitItemTableViewController.swift:294] tableView(_:cellForRowAt:) > indexPath=[2, 0]
2017-10-12 16:11:14.256 [Debug] [main] [ThisVisitItemTableViewController.swift:294] tableView(_:cellForRowAt:) > indexPath=[3, 0]
2017-10-12 16:11:15.862 [Debug] [main] [AppDelegate.swift:214] naviBackButtonPressed > sender=<UIButton: 0x7fd48e425550; frame = (0 0; 22 22); opaque = NO; layer = <CALayer: 0x604000637f20>>
2017-10-12 16:11:15.865 [Debug] [main] [AppDelegate.swift:200] navigationController(_:willShow:animated:) > curVC=<SRTDev.ShopVisitViewController: 0x7fd488e42e80>
2017-10-12 16:11:16.881 [Debug] [main] [VincentHttp.swift:31] getUrlRespJson_async(httpMethod:url:parameters:headers:requsetType:respJsonHandle:) > gCurUserItem.accessToken:Optional(“v489m85efhll5bi218tu3gc2ve”)
2017-10-12 16:11:16.881 [Debug] [main] [VincentHttp.swift:46] getUrlRespJson_async(httpMethod:url:parameters:headers:requsetType:respJsonHandle:) > currentHeaders=[“Content-Type”: “application/json; charset=UTF-8”, “authorization”: “Bearer v489m85efhll5bi218tu3gc2ve”]
2017-10-12 16:11:16.898455+0800 SRTDev[61373:4228340] dynamic_cast error 2: One or more of the following type_info’s  has hidden visibility.  They should all have public visibility.   N10__cxxabiv116__shim_type_infoE, id, N10__cxxabiv117__pbase_type_infoE.
2017-10-12 16:11:16.898647+0800 SRTDev[61373:4228340] dynamic_cast error 2: One or more of the following type_info’s  has hidden visibility.  They should all have public visibility.   N10__cxxabiv116__shim_type_infoE, id, N10__cxxabiv117__pbase_type_infoE.
2017-10-12 16:11:16.945545+0800 SRTDev[61373:4228340] [Bugly]  Trapped uncaught exception ‘NSInvalidArgumentException’, reason: ‘Invalid type in JSON write (_SwiftValue)’
(
    0   CoreFoundation                      0x000000010b17003b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x000000010c908f41 objc_exception_throw + 48
    2   CoreFoundation                      0x000000010b1e4b45 +[NSException raise:format:] + 197
    3   Foundation                          0x000000010a375a25 _writeJSONValue + 706
    4   Foundation                          0x000000010a3c5084 ___writeJSONObject_block_invoke + 176
    5   libswiftCore.dylib                  0x000000010d7a4ca3 _T0s26_SwiftDeferredNSDictionaryC23enumerateKeysAndObjectsySi7options_ys9UnmanagedVyyXlG_AGSpys5UInt8VGtXB5usingtFTfq4dgn_n + 291
    6   libswiftCore.dylib                  0x000000010d5cc4b1 _T0s26_SwiftDeferredNSDictionaryC23enumerateKeysAndObjectsySi7options_ys9UnmanagedVyyXlG_AGSpys5UInt8VGtXB5usingtF + 17
    7   libswiftCore.dylib                  0x000000010d5cc97b _T0s26_SwiftDeferredNSDictionaryC23enumerateKeysAndObjectsySi7options_ys9UnmanagedVyyXlG_AGSpys5UInt8VGtXB5usingtFTo + 43
    34  SRTDev                              0x0000000105fc4837 main + 55
    35  libdyld.dylib                       0x000000010e154d81 start + 1
)
=================================================================
Main Thread Checker: UI API called on a background thread: -[UIApplication applicationState]
PID: 61373, TID: 4231063, Thread name: (none), Queue name: com.tencent.bugly.operationQueue (QOS: USER_INTERACTIVE), QoS: 33
Backtrace:
4   SRTDev                              0x000000010650f73d -[BLYCrashLogic jceModel] + 1703
5   SRTDev                              0x00000001064fe413 -[BLYCommonUploadLogic main] + 229
    34  SRTDev                              0x0000000105fc4837 main + 55
    35  libdyld.dylib                       0x000000010e154d81 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

找到了代码的地方:

    mergedExtraPara[“parameters”] = parameters as AnyObject?
    mergedExtraPara[“headers”] = headers as AnyObject?
    gLog.debug(“currentHeaders=\(curHeaders)”)
    
    
    var paramEncoding:ParameterEncoding = JSONEncoding.default
    if (httpMethod == .get) {
        paramEncoding = URLEncoding.default
    }
    
//    let curHttpReq = Alamofire.request(url, method: httpMethod, parameters: parameters, encoding: JSONEncoding.default, headers: curHeaders)
    let curHttpReq = Alamofire.request(url, method: httpMethod, parameters: parameters, encoding: paramEncoding, headers: curHeaders)
    gLog.verbose(“curHttpReq=\(curHttpReq)”)

调用的地方:

enum TaskStatusType:Int{
    case draft              = 11  //草稿
    case toBeFilled         = 21  //待填写
    case pendingApproval    = 31  //待审批
    case rejected           = 22  //被驳回
}
        var parameters = [String : AnyObject]()
        parameters = [
            “id”: self.id as AnyObject,
            “status”: TaskStatusType.pendingApproval as AnyObject
        ]
        self.pleaseWait()
        getUrlRespJson_async(
            httpMethod: .put,
            url:  ServerApi.getShopVisitDetailsUrl(id:self.id),
            parameters: parameters,

所以需要去搞清楚,对于Alamofire的JSONEncoding解析时,需要满足什么条件

Alamofire/Alamofire: Elegant HTTP Networking in Swift

示例代码中的:

let parameters: Parameters = [
    “foo”: [1,2,3],
    “bar”: [
        “baz”: “qux”
    ]
]

参数是:Parameters的类型。

去找找这个是什么类型:

/// A dictionary of parameters to apply to a `URLRequest`.
public typealias Parameters = [String : Any]

所以,看来是需要把参数类型符合这个类型就可以了。

【总结】

此处用Alamofire参数解析JSONEncoding出错,原因是:

之前用:

        var parameters = [String : AnyObject]()
        parameters = [
            “id”: self.id as AnyObject,
            “status”: TaskStatusType.pendingApproval as AnyObject
        ]

但是其中的TaskStatusType.pendingApproval是个enum类型:

enum TaskStatusType:Int{
    case draft              = 11  //草稿
    case toBeFilled         = 21  //待填写
    case pendingApproval    = 31  //待审批
}

而不是普通的类型

改为enum的rawValue,即Int:

“status”: TaskStatusType.pendingApproval.rawValue

即可:

调试效果:

TaskStatusType.pendingApproval.rawValue可以获得Int的值31了:

然后:

let curHttpReq = Alamofire.request(url, method: httpMethod, parameters: parameters, encoding: paramEncoding, headers: curHeaders)

即可正常运行,可以格式化参数为json字符串了。

转载请注明:在路上 » 【已解决】iOS中Alamofire参数解析JSONEncoding出错

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
90 queries in 0.198 seconds, using 22.09MB memory