2016-01-20 53 views
0
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") 

这里我使用第三方类库进行签名。我怎样才能以图像的形式将它张贴到web服务?你如何在web服务中发送POST图像swift

回答

2

简单的例子:

//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 
} 

现在你可以使用这种方式:

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) 


       }) 

希望这将有助于。

+0

为什么我们使用令牌在这里? –

+0

只是一个例子,如果你需要它。如果你没有删除它。 –

1

你没有说你正在使用的第三方库,所以你可以使用Alamofire它,使用此代码:

Alamofire.upload(
    .POST, 
    "your_API_URL_here", 
    multipartFormData: { multipartFormData in 
     if let _ = image { 
      if let imageData = UIImageJPEGRepresentation(image!, 1.0) { 
       multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "file.jpeg", mimeType: "image/jpeg") 
      } else { 
       print(image) 
      } 
     } 
    }, encodingCompletion: { 
     encodingResult in 

      switch encodingResult { 
       case .Success(let upload, _, _): 
        upload.responseJSON { response in 
         switch response.result { 
          case .Success: 
           print("Success") 
          case .Failure(let error): 
           print(error) 
          } 
         } 
       case .Failure(let encodingError): 
        print(encodingError) 
       } 
      } 
     ) 
    } 
} catch _ { 

} 
+0

我正在使用第三方类来添加签名。 @iamalizade –

+0

@RakeshMohan我建议你使用'Alamofire'作这种类型的用途。这很容易使用 – iamalizade

+0

如果我有边界设置和json字符串与图像怎么办? –