2016-01-20 52 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字符串與圖像怎麼辦? –