身份验证与Alamofire一起失败

时间:2015-09-30 16:21:38

标签: swift2 ios9 alamofire bing-api

我最近将我的项目迁移到Swift 2.0并且遇到了很多错误。 我修复了大部分内容,但是这个一直出错。

我正在使用Alamofire调用Bing Search API,如下所示,我收到错误消息" Error Domain = NSCocoaErrorDomain Code = 3840"字符0周围的值无效。" UserInfo = {NSDebugDescription =字符0周围的值无效。}"

我理解这意味着身份验证失败。 有人可以告诉我如何解决这个问题吗?

let percentedKeyword = searchKey.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
Let ulrStr: String = "https://api.datamarket.azure.com/Bing/Search/v1/News" + "? Query=" + percentedKeyword! + "&$top=10&$format=JSON"
let credentials = ":\(bingApiKey)"
let plainText = credentials.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let base64 = plainText!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))

let headers = ["Authorization": "Basic \(base64)"]

Alamofire.request(.GET, urlStr, headers: headers)
    .responseJSON { request, response, data in
        switch data {
        case Result.Success(let receivedValue):
            self.bingJson = JSON(receivedValue)
        case Result.Failure(_, let error as NSError):
            print(error)
        default:
            print("do nothing")
        }
}

Xcode 7.0版 Alamofire版本2.0.2

[更新]

我尝试了网络浏览器的urlStr(" https://api.datamarket.azure.com/Bing/Search/News?Query=%E4%B8%AD%E5%9B%BD& $ top = 10& $ format = JSON")。 它要我输入用户名和密码,所以我输入apiKey作为密码,并按照Microsoft doc

的说明将用户名留空

我收到此错误:参数:查询不是String类型

根据stackoverflow,这是因为关键字不受影响,但我在关键字字符串中添加了百分比......

1 个答案:

答案 0 :(得分:1)

事实证明,我需要搜索关键词的单引号。

let percentedKeyword = searchKey.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
        let urlStr: String = "https://api.datamarket.azure.com/Bing/Search/News" + "?Query=" + "'" + percentedKeyword! + "'" + "&$top=10&$format=JSON"
        let credentials = ":\(bingApiKey)"
        let plainText = credentials.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
        let base64 = plainText!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))

        let headers = ["Authorization": "Basic \(base64)"]

        Alamofire.request(.GET, urlStr, headers: headers)
            .responseJSON { request, response, data in
                switch data {
                case Result.Success(let receivedValue):
                    self.bingJson = JSON(receivedValue)
                case Result.Failure(_, let error as NSError):
                    print(error)
                default:
                    print("do nothing")
                }
        }
    }