Sometimes we need to send the images to a server by taking images from media library or by a camera for this we need to follow some steps.
Here are some steps:
1: Enter the key in info.plist file in a project
a: Media library usage description.
b: photo library usage description.
c: camera usage description.
2: Write this code to access the camera or media library of your phone.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
let AC = UIAlertController(title: "Upload Profile Banner", message: "", preferredStyle: .alert) let clickBtn = UIAlertAction(title: "Take Picture", style: .default, handler: {(_ action: UIAlertAction) -> Void in if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.camera; imagePicker.allowsEditing = false self.present(imagePicker, animated: true, completion: nil) } }) let cameraRollBtn = UIAlertAction(title: "Upload Picture From Camera Roll", style: .default, handler: {(_ action: UIAlertAction) -> Void in let picker = UIImagePickerController() picker.delegate = self picker.allowsEditing = true picker.sourceType = .photoLibrary self.present(picker, animated: true, completion: { _ in }) }) let noBtn = UIAlertAction(title: "Cancel", style: .default, handler: {(_ action: UIAlertAction) -> Void in }) AC.addAction(clickBtn) AC.addAction(cameraRollBtn) AC.addAction(noBtn) self.parent!.present(AC, animated: true, completion: { _ in }) |
3: Now there are one thing to add in current View controller.
1 |
UIImagePickerControllerDelegate,UINavigationControllerDelegate |
4: There is one delegate method that will receive the image from either camera or media library.
1 2 3 4 5 6 7 8 |
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let image = info[UIImagePickerControllerOriginalImage] as? UIImage { imageData = UIImageJPEGRepresentation(image, 0.8) as NSData! uploadImage = "true"; } picker.dismiss(animated: true, completion: nil); } |
5: Now we need to send the image to server:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
let request = NSMutableURLRequest(url: URL(string: imageSendUrl)!) request.httpMethod = "POST" request.cachePolicy = .reloadIgnoringLocalCacheData let boundary = "unique-consistent-string" //define the multipart request type request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") let body = NSMutableData() let screenWidth:String = String(format:"%f",SCREEN_WIDTH); // add params (all params are strings) body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!) body.append("Content-Disposition: form-data; name=\("customerId")\r\n\r\n".data(using: String.Encoding.utf8)!) body.append("\(customerId)\r\n".data(using: String.Encoding.utf8)!) body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!) body.append("Content-Disposition: form-data; name=\("width")\r\n\r\n".data(using: String.Encoding.utf8)!) body.append("\(screenWidth)\r\n".data(using: String.Encoding.utf8)!) // add image data if (imageData != nil) { body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!) body.append("Content-Disposition: form-data; name=\("imageFormKey"); filename=imageName.jpg\r\n".data(using: String.Encoding.utf8)!) body.append("Content-Type: image/jpeg\r\n\r\n".data(using: String.Encoding.utf8)!) body.append(imageData as Data) body.append("\r\n".data(using: String.Encoding.utf8)!) } body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!) request.httpBody = body as Data let session = URLSession.shared let task = session.dataTask(with: request as URLRequest) { ( data, response, error) in guard let _:NSData = data as NSData?, let _:URLResponse = response, error == nil else { print("error") self.view.isUserInteractionEnabled = true SVProgressHUD.dismiss() SVProgressHUD.setDefaultStyle(SVProgressHUDStyle.dark) SVProgressHUD.showError(withStatus:"Something error , Please Try Again..."); return } if let httpResponse = response as? HTTPURLResponse { print(httpResponse.statusCode) if(httpResponse.statusCode == 200){ if(self.imageForCategoryMenu == "uploadBannerPic"){ let imageUrl = String(format:"%@/media/customerpicture/%@/%fx%d/%@-banner.jpg", IMAGE_URL, customerId, SCREEN_WIDTH, (Int)(SCREEN_WIDTH/2), customerId) let url = NSURL(string: imageUrl ) as! URL let operation1 = BlockOperation(block: { let data = try? Data(contentsOf: url) let img = UIImage(data: data!) OperationQueue.main.addOperation({ self.ic_profile_banner.image = img }) }) self.queue.addOperation(operation1) do{ let largeImageData = try Data(contentsOf: url) let bannerImage:UIImage = UIImage(data: largeImageData)! if (bannerImage.size.height != 0) { self.profileImageCache.setObject(bannerImage, forKey: (url) as AnyObject) } }catch{ print("error"); } defaults.set(imageUrl, forKey: "profileBanner") } |