在iOS 9问题上使用Alamofire上传带有URL参数的图像

时间:2015-10-01 13:01:40

标签: swift2 ios9 alamofire

我有一个用Swift 2.0编写的iOS应用程序,它将图像上传到Microsoft Azure Blob Storage。我使用Alamofire来提出要求。

iOS 8 的设备上,一切正常,但在iOS 9上上传时出错:

    let AlamofireManager = Alamofire.Manager.sharedInstance
    AlamofireManager.session.configuration.HTTPAdditionalHeaders = [
        "Content-Type": "image/jpg",
        "x-ms-blob-type": "BlockBlob"
    ]
    AlamofireManager.upload(.PUT, uploadURL, data: imageData)
        .responseJSON { (request, response, result) in
            print("Request=\(request)")
            print("response=\(response)")
            print("result=\(result)")
            if (response) != nil {
                let statusString = String(stringInterpolationSegment: response!.statusCode)
                let statusCode = self.getStatusCodeFromStatusString(statusString)
                if (statusCode == 201) {
                    // MY SUCCESS CODE IS HERE
                }
                else {
                    // STATUSCODE != 201
                }
            }
            else {
                // OTHER ERROR
            }
       }

上传的示例网址(uploadURL)可能是:

https://mystorage.blob.core.windows.net:443/thumbs/7346e38a-eb54-48ea-b0fe-89357100dd18.jpg?sv=2013-08-15&sr=b&sig=GYwHvnUc52GsajFJCAu1v4W5qG0wSBpaXvxncD%2FAt34%3D&st=2015-10-01T11%3A25%3A57Z&se=2015-10-01T11%3A40%3A57Z&sp=w

对于Azure,重要的是: a)HTTP-Verb为PUT b)Url参数包含在Url中,而不是多部分数据(这是上传的访问令牌)。

也许Alamofire在创建带参数的URL和PUT时遇到了问题?

此解决方案不起作用,因为它基于多部分数据上传:Upload image with parameters in Swift

因为我考虑了URL参数问题,所以我尝试了以下内容:

    let AlamofireManager = Alamofire.Manager.sharedInstance
    AlamofireManager.session.configuration.HTTPAdditionalHeaders = [
        "Content-Type": "image/jpg",
        "x-ms-blob-type": "BlockBlob"
    ]
    var URLRequest: NSMutableURLRequest {
        let URL = NSURL(string: uploadURL)!
        var mutableRequest = NSMutableURLRequest(URL: URL)
        mutableRequest.HTTPMethod = Alamofire.Method.PUT.rawValue
        return mutableRequest
    }
    AlamofireManager.upload(URLRequest, data: imageData)
:
: rest is same like above
:

但这也行不通。在这两种情况下,我总是从服务器获得400错误(response.statusCode)。 result包含Failure,信息NSCocoaErrorDomain - code 3840包含说明Invalid value around character 3

但是在iOS 8上,解决方案就像一个魅力:(

任何想法,问题是什么以及如何解决它?

编辑:或者端口是否有问题?

1 个答案:

答案 0 :(得分:0)

自己搞定。 Alamofire似乎没有像AlamofireManager那样发送HTTP-Headers。我手动添加了标题:

    var URLRequest: NSMutableURLRequest {
        let URL = NSURL(string: uploadURL)!
        var mutableRequest = NSMutableURLRequest(URL: URL)
        mutableRequest.HTTPMethod = Alamofire.Method.PUT.rawValue
        mutableRequest.setValue("image/jpg", forHTTPHeaderField: "Content-Type")
        mutableRequest.setValue("BlockBlob", forHTTPHeaderField: "x-ms-blob-type")
        return mutableRequest
    }

    AlamofireManager.upload(URLRequest, data: imageData)
    :
    :