自从iOS 9开始,我在使用Alamofire上传带有参数的图片时遇到了什么问题,该怎么回事?

时间:2015-10-25 07:09:20

标签: swift ios9 alamofire

我的应用上传很好,服务器没有更改,也没有代码。但是,一旦我的手机更新到iOS 9,标题就没有正确传递。我的服务器一直在返回未经授权的访问,因为我认为我附加标题的方式与我在用户标记帖子时附加标题的方式不同。

澄清一下:代码没有改变,但软件确实如此。我确信它是图像上传,因为只有两个调用此样式的alamofire标头,因为传递带参数的图像。它们都返回相同的服务器消息"未经授权的访问"。这不是凭证的问题,因为授权的相同标题被传递给在我的api中撰写评论或标记帖子,并且它们都可以正常工作。

以下是完整图片上传的代码:

    let imageData = UIImageJPEGRepresentation(newAlbumPhoto.originalImage!, 0.20)
    let urlRequest = self.urlRequestWithComponents(Globals.baseURL + "postphotoalbumphotos/" + String(id), parameters: parameters, imageData: imageData!)
    let plainString = "\(user.username!):\(user.encryptedPassword)" as NSString
    let plainData = plainString.dataUsingEncoding(NSUTF8StringEncoding)
    let base64String = plainData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
    Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = ["Authorization": "Basic " + base64String!]

    Alamofire.upload(urlRequest.0, data: urlRequest.1)
        .responseJSON { request, response, result in
            switch result {
            case .Success(let JSON):
                completion(results: JSON, error: nil)
            case .Failure(let data, let error):
                if let dataCompletion = data {
                    completion(results: dataCompletion, error: nil)
                }
                if let error = error as ErrorType? {
                    completion(results: nil, error: error)
                }
            }
    }

这是urlRequestWithComponents方法:

func urlRequestWithComponents(urlString:String, parameters:Dictionary<String, AnyObject>, imageData:NSData) -> (URLRequestConvertible, NSData) {

    // create url request to send
    let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: urlString)!)
    mutableURLRequest.HTTPMethod = Alamofire.Method.POST.rawValue
    let boundaryConstant = "myRandomBoundary12345";
    let contentType = "multipart/form-data;boundary="+boundaryConstant
    mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")

    // create upload data to send
    let uploadData = NSMutableData()

    // add image
    uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    uploadData.appendData("Content-Disposition: form-data; name=\"file\"; filename=\"file.png\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    uploadData.appendData("Content-Type: image/png\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    uploadData.appendData(imageData)

    // add parameters
    for (key, value) in parameters {
        uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!)
    }
    uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    // return URLRequestConvertible and NSData
    return (Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0, uploadData)
}

最后,我应该发布另一段我的代码,这些代码生成相同的auth标题,但是IS正在运行:

let plainString = "\(user.username!):\(user.encryptedPassword)" as NSString
let plainData = plainString.dataUsingEncoding(NSUTF8StringEncoding)
let base64String = plainData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
let header = ["Authorization": "Basic " + base64String!]

    Alamofire.request(.POST, Globals.baseURL + "flagpost/", parameters: ["user": user.username!, "photoID": id!], headers: header)
        .responseJSON { request, response, result in
            switch result {
            case .Success(let JSON):
                completion(results: JSON, error: nil)
            case .Failure(let data, let error):
                if let dataCompletion = data {
                    completion(results: dataCompletion, error: nil)
                }
                if let error = error as ErrorType? {
                    completion(results: nil, error: error)
                }
            }
    }

1 个答案:

答案 0 :(得分:0)

您可以在代码

下使用 Alamofire 3.0 +
func uploadImageAndData(){
  //parameters
    let gender    = "M"
    let firstName = "firstName"
    let lastName  = "lastName"
    let dob       = "11-Jan-2000"
    let aboutme   = "aboutme"
    let token     = "token"


    var parameters = [String:AnyObject]()
    parameters = ["gender":gender,"firstName":firstName,"dob":dob,"aboutme":aboutme,"token":token,"lastName":lastName]

    let URL = "http://yourserviceurl/"

let image = UIImage(named: "image.png")

Alamofire.upload(.POST, URL, multipartFormData: {
multipartFormData in
if  let imageData = UIImageJPEGRepresentation(image, 0.6) {
multipartFormData.appendBodyPart(data: imageData, name: "image", fileName: "file.png", mimeType: "image/png")
}


for (key, value) in parameters {
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
}

}, encodingCompletion: {
encodingResult in

switch encodingResult {
case .Success(let upload, _, _):
    print("s")
        upload.responseJSON { response in
            print(response.request)  // original URL request
            print(response.response) // URL response
            print(response.data)     // server data
            print(response.result)   // result of response serialization

            if let JSON = response.result.value {
                print("JSON: \(JSON)")
            }
    }

case .Failure(let encodingError):
print(encodingError)
}
})
}