Monday, 24 September 2018

Upload Image to server in Swift


Upload image to server in Swift 4.1 and Xcode 9.4.1

Here i'm posting only Upload image code.

In this below code you need to replace your "image file name and uploaded file name".


Call this function like :  uploadImageOne()


func uploadImageOne(){
        
    let imageData = UIImageJPEGRepresentation(yourImage!, 1.0)//Replace your image
        
    if imageData != nil{
       var request = URLRequest(url: NSURL(string:urlString)! as URL)//Send your URL here
       print(request)

       request.httpMethod = "POST"
            
       let boundary = NSString(format: "---------------------------14737809831466499882746641449")
       let contentType = NSString(format: "multipart/form-data; boundary=%@",boundary)
       //  println("Content Type \(contentType)")
       request.addValue(contentType as String, forHTTPHeaderField: "Content-Type")
            
       var body = Data()
            
       body.append(NSString(format: "\r\n--%@\r\n", boundary).data(using: String.Encoding.utf8.rawValue)!)
       body.append(NSString(format:"Content-Disposition: form-data;name=\"title\"\r\n\r\n").data
                            (using:String.Encoding.utf8.rawValue)!)
       body.append("Hello".data(using: String.Encoding.utf8, allowLossyConversion: true)!)

            
       body.append(NSString(format: "\r\n--%@\r\n", boundary).data(using: String.Encoding.utf8.rawValue)!)
       body.append(NSString(format:"Content-Disposition: form-data;name=\"uploaded_file\";filename=\"image.jpg\"\\r\n").data
                           (using:String.Encoding.utf8.rawValue)!) //Here replace your image name and file name
       body.append(NSString(format: "Content-Type: image/jpeg\r\n\r\n").data(using: String.Encoding.utf8.rawValue)!)
       body.append(imageData!)
       body.append(NSString(format: "\r\n--%@\r\n", boundary).data(using: String.Encoding.utf8.rawValue)!)
            
       request.httpBody = body
            
       let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil     
           else { // check for fundamental networking error
           print("error=\(String(describing: error))")
           SharedClass.sharedInstance.alert(view: self, message: "\(String(describing: error!.localizedDescription))")
           return
        }
                
        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 500 {
            SharedClass.sharedInstance.alert(view: self, message: "Server Error")
        } else if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
             print("statusCode should be 200, but is \(httpStatus.statusCode)")
             print("response = \(String(describing: response))")
        }
      
        //This can print your response in string formate        
        let responseString = String(data: data, encoding: .utf8)
         //            let dictionary = data
         //            print("dictionary = \(dictionary)")
         print("responseString = \(String(describing: responseString!))")
                
         do {
             self.response3 = (try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject])!
             print(self.response3)
                    
             if (((self.response3["Response"] as? [String : Any])?["status"]) as! String == "SUCCESS") {
                   let message = (self.response3["Response"] as? [String : Any])?["message"] as? String
                       SharedClass.sharedInstance.alert(view:self, message: message)
              } else {
                    let message = (self.response3["Response"] as? [String : Any])?["message"] as? String
                        SharedClass.sharedInstance.alert(view:self, message: message)
                    }

          } catch let error as NSError {
               print(error)
               print(error.localizedDescription)
          }
       }
            
        task.resume()
            
     }
        

    }

Difference between == and ===

Difference between == and === https://stackoverflow.com/questions/24002819/difference-between-and == operator checks if their ...