swift - 尝试连接到我的服务器时使用 Alamofire 和 swift 出现 401 错误

标签 swift ios7 alamofire

好吧,我正在尝试将 json 文件作为字符串下载,然后将其解析出来。但我必须先从我的网页下载它。该网页需要用户名和密码才能访问。这给了我一个 401 错误,所以它不发送用户名或密码。如何将用户名和密码添加到请求中?

 print("Downloading the json file")
    let plainString = "\(myUserName):\(myPassword)" as NSString
    let plainData = plainString.dataUsingEncoding(NSUTF8StringEncoding)
    let base64String = plainData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))

    Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = ["Authorization": "Basic " + base64String!]

    Alamofire.request(.GET, promoUrl)
        .response {(request, response, _, error) in
            print(response)
    }

这是结果

Optional(<NSHTTPURLResponse: 0x7fe103818790> { URL: http://xxxapi/1.0/promotions } { status code: 401, headers {
"Cache-Control" = "no-cache, no-store, max-age=0, must-revalidate";
Connection = "keep-alive";
"Content-Length" = 186;
"Content-Type" = "application/json;charset=UTF-8";
Date = "Thu, 12 May 2016 01:36:33 GMT";
Expires = 0;
Pragma = "no-cache";
Server = "Apache-Coyote/1.1";
"Www-Authenticate" = "Basic realm=\"Realm\"";
"X-Content-Type-Options" = nosniff;
"X-Frame-Options" = DENY;
"X-XSS-Protection" = "1; mode=block";

非常感谢您对此提供的任何帮助

最佳答案

大家好,经过一番努力,我让它工作了。我把上面的所有东西都扔掉了,变得简单了。它效果更好并且更容易做到

这是任何想要它的人的工作代码

    Alamofire.request(.GET, promoUrl, parameters: [myUserName:myPassword])
        .authenticate(user: myUserName, password: myPassword)
        .response {(request, response, data, error) in
            print(response)


    }

主要区别在于

parameters: [myUserName:myPassword]

这会将我的密码和用户名加载到网址中。这可能不是最好的方法,但它目前可以满足我的需求

关于swift - 尝试连接到我的服务器时使用 Alamofire 和 swift 出现 401 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37175916/

相关文章:

swift - 在 Swift 中迭代部分字符串

ios - 将 CIImage 实例转换为 CGImage 实例然后再转换为 UIImage 的原因

ios7 - AVAudioPlayer 不适用于 iOS7

ios - 使用 arc4Random 设置 Sprite 垂直位置的限制

ios - 当放置在 TabBarController 中时,按钮会出现在 View 之外,否则不会出现?

iOS 7 UIViewController(带导航栏)不插入 UIScrollView

ios - Codables 错误与 Alamofire "Cannot convert value of type ' [字符串 : Any ]' to expected argument type ' Data'"

python - Alamofire 将 PNG 上传到具有白色背景的 Flask

php - Swift 上传图片,服务器响应说文件不是图片?

swift - 为什么我的渐变层比我应用它的 UITextField 小?