当移动到cocoapod时,Swift Routing枚举崩溃

时间:2016-04-28 00:31:07

标签: swift cocoapods alamofire

我最近一直在将代码重构为基础cocoapod,以便在多个项目中使用。其中一个类是Alamofire的一个相当陈规定型的路由枚举。它一直工作正常,直到被搬进cocoapod ......现在正在崩溃。示例实现:

public enum Router: URLRequestConvertible {

    static var baseURLString = "http://myserver.com/api"

    case Endpoint1(String, String)
    case Endpoint2(String, String, Date, Date)
    case Endpoint3(String, String)

    public var URLRequest: NSMutableURLRequest {
        var path : String! {
            switch self {
            case .Endpoint1(let id, _):
                return "/endpoint1/" + id
            case .Endpoint2(let id, _, _, _):
                return "/booking/\(id)/thing"
            case .Endpoint3(_, _):
                return "/authenticate"
            }
        }

        var parameters: [String: AnyObject] {
            switch self {
            case .Endpoint2(_, _, let startDate, let endDate):
                let params = ["startDate": startDate, "endDate" : endDate]
                return params
            default:
                let params = [String: AnyObject]()
                return params
            }
        }

        var method :  Alamofire.Method {
            switch self {
            case .Endpoint2:
                return .POST
            default:
                return .GET
            }
        }

        var body : [String : AnyObject]?{
            switch self{
            case .Endpoint3(let email, let password):
                return ["email" : "\(email)", "password" : "\(password)"]
            default:
                return nil
            }
        }

        var header : [String: String]?{
            switch self {
            case .Endpoint1(_, let token):
                return ["x-access-token" : token]
            default:
                return nil
            }
        }

        let URL = NSURL(string: Router.baseURLString)?.URLByAppendingPathComponent(path)
        let request = NSURLRequest(URL: URL!)

        let encoding = Alamofire.ParameterEncoding.URL

        let mutable = (encoding.encode(request, parameters: parameters).0)
        mutable.HTTPMethod = method.rawValue

        if let bodyParams = body{
            mutable.setValue("application/json", forHTTPHeaderField: "Content-Type")
            mutable.addJsonArrayToRequestBody(bodyParams)
        }

        if let headerParams = header{
            for param in headerParams{
                mutable.setValue(param.1, forHTTPHeaderField: param.0)
            }
        }

        return mutable
    }
}

失败线是:

for param in headerParams{

但由于它是在开发cocoapod中,我无法将调试器附加到该点,错误也不会超过EXEC_BAD_INSTRUCTION,这对于帮助不大。如何进一步调试导致错误的原因?

1 个答案:

答案 0 :(得分:0)

这是使用开发cocoapod时xcode调试器中的错误,实际错误是:

让URL = NSURL(字符串:Router.baseURLString)?. URLByAppendingPathComponent(path)

调用此方法时尚未设置静态baseURLString,导致URL为nil。我已经看到多次出现的调试器在现在共享的代码中指出了不正确的行,不知道如何修复。