Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/100.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何在web服务swift中以POST方式发送图像_Ios_Swift_Post - Fatal编程技术网

Ios 如何在web服务swift中以POST方式发送图像

Ios 如何在web服务swift中以POST方式发送图像,ios,swift,post,Ios,Swift,Post,这里我使用第三方类库作为签名。如何以图像的形式将其发布到Web服务?简单示例: var urlString = "" let url = NSURL(string: urlString) let theRequest = NSMutableURLRequest(URL: url!) theRequest.HTTPMethod = "POST" let parameters = [] var err:NSError! do{

这里我使用第三方类库作为签名。如何以图像的形式将其发布到Web服务?

简单示例:

    var urlString = ""

    let url = NSURL(string: urlString)

    let theRequest = NSMutableURLRequest(URL: url!)

    theRequest.HTTPMethod = "POST"

    let parameters = []

    var err:NSError!

    do{
        theRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters, options: [])
    }

    catch let error as NSError{

        err = error
        theRequest.HTTPBody = nil

    }

    theRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
    theRequest.addValue("application/json", forHTTPHeaderField: "Accept")
助手功能:

//create session
var urlSession : NSURLSession!

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
urlSession = NSURLSession(configuration: configuration)

func updateUserDetails(image : UIImage? , dictUserDetails: [String: String?] ,completionClosure: (repos :NSDictionary) ->())  {

    let request = NSMutableURLRequest(URL: NSURL(string:"Your URL" )!)
    request.HTTPMethod = "POST"
    let boundary = generateBoundaryString()

    let token = getUserToken() as String
    request.addValue("Token " + token, forHTTPHeaderField: "Authorization") // add token if you need
    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

    guard image != nil else {
        request.HTTPBody = createBodyWithParameters(dictUserDetails, filePathKey: "profile_pic", imageDataKey: nil, boundary: boundary)

        let postDataTask = self.urlSession.dataTaskWithRequest(request, completionHandler: {(data, response, error) in

            if (error != nil) {
                print(error!.localizedDescription)
            }

            if (data != nil) {
                if let jsonResult: NSDictionary  = (try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as? NSDictionary
                {
                    completionClosure(repos: jsonResult)
                }
                else
                {
                    completionClosure(repos: NSDictionary())
                }
            } else {
                completionClosure(repos: NSDictionary())
            }

        })
        postDataTask.resume()

        return
    }

    let imageData = UIImageJPEGRepresentation(image!, 0.3)

    request.HTTPBody = createBodyWithParameters(dictUserDetails, filePathKey: "profile_pic", imageDataKey: imageData, boundary: boundary)

    let postDataTask = self.urlSession.dataTaskWithRequest(request, completionHandler: {(data, response, error) in

        if (error != nil) {
            print(error!.localizedDescription)
        }

        if (data != nil) {
            if let jsonResult: NSDictionary  = (try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as? NSDictionary
            {
                completionClosure(repos: jsonResult)
            }
            else
            {
                completionClosure(repos: NSDictionary())
            }
        } else {
            completionClosure(repos: NSDictionary())
        }

    })
    postDataTask.resume()
}
现在您可以这样使用它:

//Generate boundary
func generateBoundaryString() -> String {
    return "Boundary-\(NSUUID().UUIDString)"
}

//create body
func createBodyWithParameters(parameters: [String: String?]?, filePathKey: String?, imageDataKey: NSData?, boundary: String) -> NSData {
    let body = NSMutableData()

    if parameters != nil {

        for (key, value) in parameters! {

            if value != nil {

                body.appendString("--\(boundary)\r\n")
                body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                body.appendString("\(value!)\r\n")
            }
        }
    }

    if imageDataKey != nil
    {
        let filename = "user-profile.jpg"
        let mimetype = "image/jpg"

        body.appendString("--\(boundary)\r\n")
        body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
        body.appendString("Content-Type: \(mimetype)\r\n\r\n")
        body.appendData(imageDataKey!)
        body.appendString("\r\n")

        body.appendString("--\(boundary)--\r\n")
    }

    return body
}

希望能有所帮助。

简单的例子:

    var urlString = ""

    let url = NSURL(string: urlString)

    let theRequest = NSMutableURLRequest(URL: url!)

    theRequest.HTTPMethod = "POST"

    let parameters = []

    var err:NSError!

    do{
        theRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters, options: [])
    }

    catch let error as NSError{

        err = error
        theRequest.HTTPBody = nil

    }

    theRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
    theRequest.addValue("application/json", forHTTPHeaderField: "Accept")
助手功能:

//create session
var urlSession : NSURLSession!

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
urlSession = NSURLSession(configuration: configuration)

func updateUserDetails(image : UIImage? , dictUserDetails: [String: String?] ,completionClosure: (repos :NSDictionary) ->())  {

    let request = NSMutableURLRequest(URL: NSURL(string:"Your URL" )!)
    request.HTTPMethod = "POST"
    let boundary = generateBoundaryString()

    let token = getUserToken() as String
    request.addValue("Token " + token, forHTTPHeaderField: "Authorization") // add token if you need
    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

    guard image != nil else {
        request.HTTPBody = createBodyWithParameters(dictUserDetails, filePathKey: "profile_pic", imageDataKey: nil, boundary: boundary)

        let postDataTask = self.urlSession.dataTaskWithRequest(request, completionHandler: {(data, response, error) in

            if (error != nil) {
                print(error!.localizedDescription)
            }

            if (data != nil) {
                if let jsonResult: NSDictionary  = (try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as? NSDictionary
                {
                    completionClosure(repos: jsonResult)
                }
                else
                {
                    completionClosure(repos: NSDictionary())
                }
            } else {
                completionClosure(repos: NSDictionary())
            }

        })
        postDataTask.resume()

        return
    }

    let imageData = UIImageJPEGRepresentation(image!, 0.3)

    request.HTTPBody = createBodyWithParameters(dictUserDetails, filePathKey: "profile_pic", imageDataKey: imageData, boundary: boundary)

    let postDataTask = self.urlSession.dataTaskWithRequest(request, completionHandler: {(data, response, error) in

        if (error != nil) {
            print(error!.localizedDescription)
        }

        if (data != nil) {
            if let jsonResult: NSDictionary  = (try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as? NSDictionary
            {
                completionClosure(repos: jsonResult)
            }
            else
            {
                completionClosure(repos: NSDictionary())
            }
        } else {
            completionClosure(repos: NSDictionary())
        }

    })
    postDataTask.resume()
}
现在您可以这样使用它:

//Generate boundary
func generateBoundaryString() -> String {
    return "Boundary-\(NSUUID().UUIDString)"
}

//create body
func createBodyWithParameters(parameters: [String: String?]?, filePathKey: String?, imageDataKey: NSData?, boundary: String) -> NSData {
    let body = NSMutableData()

    if parameters != nil {

        for (key, value) in parameters! {

            if value != nil {

                body.appendString("--\(boundary)\r\n")
                body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                body.appendString("\(value!)\r\n")
            }
        }
    }

    if imageDataKey != nil
    {
        let filename = "user-profile.jpg"
        let mimetype = "image/jpg"

        body.appendString("--\(boundary)\r\n")
        body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
        body.appendString("Content-Type: \(mimetype)\r\n\r\n")
        body.appendData(imageDataKey!)
        body.appendString("\r\n")

        body.appendString("--\(boundary)--\r\n")
    }

    return body
}

希望对您有所帮助。

您没有说明您使用的是哪一个第三方库,因此您可以使用
Alamofire
进行此操作,使用以下代码:

updateUserDetails(yourImage, dictUserDetails: [

                    //parameters example
                    "date_of_birth": birthDate,
                    "first_name": firstName,
                    "last_name" : lastName,
                    "email" : email,
                    "phone_number" : phoneNumber,
                    "address" : address,
                    "martial_status" : userMaritialStatus

                    ], completionClosure: { (repos) -> () in

                        print(repos)


                })

您没有说明您使用的是哪一个第三方库,因此您可以使用以下代码对其使用
Alamofire

updateUserDetails(yourImage, dictUserDetails: [

                    //parameters example
                    "date_of_birth": birthDate,
                    "first_name": firstName,
                    "last_name" : lastName,
                    "email" : email,
                    "phone_number" : phoneNumber,
                    "address" : address,
                    "martial_status" : userMaritialStatus

                    ], completionClosure: { (repos) -> () in

                        print(repos)


                })

我正在使用第三方类添加签名@iamalizade@RakeshMohan我建议您使用
Alamofire
进行此类输入。使用起来很简单,如果我有边界要设置,那么该怎么办?我正在使用第三方类添加签名@iamalizade@RakeshMohan我建议您使用
Alamofire
进行此类输入。使用起来很简单,如果我有边界要设置,那么该怎么办?为什么我们在这里使用令牌?如果您需要,就举个例子。如果您不删除它。为什么我们在这里使用令牌?如果您需要它,请举个例子。如果没有,请将其移除。