Skip to content

Commit

Permalink
Improve postprocessing of new machines (#121)
Browse files Browse the repository at this point in the history
* feat: postprocess title/area

* feat: postprocess address

* feat: postprocess address

* change pull request routing to commit everything to the data branch

* fix import

* debug fuzzy search and gmaps api to newest version

* rename branch to final name

* bug fixes in app after testing

* make frontend display http responses

* refactor: simplify ID computation

* chore: improve user messages

* refactor: add labels to PR

* change flask url and add response text for connection failures

* version update message

* show loading wheel and then alert with correct message

---------

Co-authored-by: NinaWie <[email protected]>
  • Loading branch information
jannisborn and NinaWie authored Aug 25, 2023
1 parent b183660 commit 85b1ee5
Show file tree
Hide file tree
Showing 11 changed files with 741 additions and 237 deletions.
4 changes: 2 additions & 2 deletions PennyMe.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -501,7 +501,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.8;
MARKETING_VERSION = 1.9;
PRODUCT_BUNDLE_IDENTIFIER = "PennyMe--com.de.pennyme";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 4.2;
Expand All @@ -521,7 +521,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.8;
MARKETING_VERSION = 1.9;
PRODUCT_BUNDLE_IDENTIFIER = "PennyMe--com.de.pennyme";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 4.2;
Expand Down
99 changes: 61 additions & 38 deletions PennyMe/NewMachineRequest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ struct ConfirmationMessageView: View {
}
}

@available(iOS 13.0, *)
@available(iOS 14.0, *)
struct RequestFormView: View {
let coords: CLLocationCoordinate2D
// Properties to hold user input
Expand All @@ -88,13 +88,12 @@ struct RequestFormView: View {
@State private var paywall: Bool = false
@State private var multimachine: String = ""
@State private var showFinishedAlert = false
@State private var submittedName: String = ""
@State private var displayResponse: String = ""
@Environment(\.presentationMode) private var presentationMode // Access the presentationMode environment variable
@State private var selectedImage: UIImage? = nil
@State private var isImagePickerPresented: Bool = false
@State private var isSubmitting = false
@State private var showAlert = false
@State private var submitted = false
@State private var isLoading = false

@State private var keyboardHeight: CGFloat = 0
private var keyboardObserver: AnyCancellable?
Expand Down Expand Up @@ -159,31 +158,28 @@ struct RequestFormView: View {
}
.padding()


// Submit button
Button(action: {
submitRequest()
}) {
Text("Submit")
if isLoading {
ProgressView("Loading...")
.padding()
.foregroundColor(Color.white)
.frame(maxWidth: .infinity)
.background(Color.blue)
.cornerRadius(10)
}.padding().disabled(isSubmitting)

// Enter all info
Text("\(submittedName)").foregroundColor(Color.red)
} else {
Button(action: {
submitRequest()
}) {
Text("Submit")
.padding()
.foregroundColor(Color.white)
.frame(maxWidth: .infinity)
.background(Color.blue)
.cornerRadius(10)
}.padding().disabled(isLoading)
}

AlertPresenter(showAlert: $showFinishedAlert, title: "Finished", message: "Thanks for adding this machine. We will review this request and the machine will be added shortly.")
AlertPresenter(showAlert: $showFinishedAlert, title: "Finished", message: "Thanks for suggesting this machine. We will review this request shortly. Note that it can take up to a few days until the machine becomes visible.")
.padding()
}
.alert(isPresented: $showAlert) {
Alert(title: Text("Processing"), message: Text("Please wait..."), dismissButton: .default(Text("Dismiss")))
}
.onAppear {
// Call the private function to regulate the machine
checkRequest()
Alert(title: Text("Attention!"), message: Text(displayResponse), dismissButton: .default(Text("Dismiss")))
}
.padding()
.navigationBarTitle("Add new machine")
Expand All @@ -194,37 +190,35 @@ struct RequestFormView: View {
.padding(.bottom, keyboardHeight)
}

private func checkRequest() {
if submitted{
showAlert = true
}
private func finishLoading(message: String) {
displayResponse = message
showAlert = true
isLoading = false
}

// Function to handle the submission of the request
private func submitRequest() {
submitted = true
isLoading = true
if name == "" || address == "" || area == "" || selectedImage == nil {
submittedName = "Please enter all information & upload image"
finishLoading(message: "Please enter all information & upload image")
} else {
showAlert = true
// correct multimachine information
if multimachine == "" {
multimachine = "1"
}
isSubmitting = true
// upload image and make request
if let image = selectedImage! as UIImage ?? nil {
// Convert the image to a data object
guard let imageData = image.jpegData(compressionQuality: 1.0) else {
print("Failed to convert image to data")
submittedName = "Something went wrong with your image"
finishLoading(message: "Something went wrong with your image")
return
}
// call flask method called create_machine
let urlString = flaskURL+"/create_machine?title=\(name)&address=\(address)&lat_coord=\(coords.latitude)&lon_coord=\(coords.longitude)&multimachine=\(multimachine)&paywall=\(paywall)&area=\(area)"
guard let url = URL(string: urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "None"
) else {
submittedName = "Something went wrong. Please try to re-enter the information"
finishLoading(message: "Something went wrong. Please try to re-enter the information")
return
}
var request = URLRequest(url: url)
Expand All @@ -244,13 +238,42 @@ struct RequestFormView: View {
// Create a URLSessionDataTask to send the request
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
print("Error: \(error)")
finishLoading(message: "Something went wrong. Please check your internet connection and try again")
return
}
DispatchQueue.main.async {
self.showFinishedAlert = true
self.presentationMode.wrappedValue.dismiss()
isSubmitting = false
// Check if a valid HTTP response was received
guard let httpResponse = response as? HTTPURLResponse else {
finishLoading(message: "Something went wrong. Please check your internet connection and try again")
return
}
// Extract the status code from the HTTP response
let statusCode = httpResponse.statusCode

// Check if the status code indicates success (e.g., 200 OK)
if 200 ..< 300 ~= statusCode {
// everything worked, finish
DispatchQueue.main.async {
self.showFinishedAlert = true
self.presentationMode.wrappedValue.dismiss()
isLoading = false
}
}
else {
if let responseData = data {
do {
// Parse the JSON response
if let json = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: Any] {
// Handle the JSON data here
if let answerString = json["error"] as? String {
finishLoading(message: answerString)
return
}
}
} catch {
print("JSON parsing error: \(error)")
finishLoading(message: "Something went wrong. Please check your internet connection and try again")
}
}
}
}
task.resume()
Expand Down
4 changes: 2 additions & 2 deletions PennyMe/PinViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import MapKit

var FOUNDIMAGE : Bool = false

let flaskURL = "http://37.120.179.15:5000/"
let flaskURL = "http://37.120.179.15:6006/"
let imageURL = "http://37.120.179.15:8000/"

class PinViewController: UITableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
Expand Down Expand Up @@ -289,7 +289,7 @@ class PinViewController: UITableViewController, UIImagePickerControllerDelegate,
func chooseImage() {
if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){
// Create the alert controller
let alertController = UIAlertController(title: "Attention!", message: "Your image will be shown to all users of the app! Please be considerate. Upload only images that are strictly related to penny machines. With the upload, you grant the PennyMe team the unrestricted right to process, alter, share, distribute and publicly expose this image.", preferredStyle: .alert)
let alertController = UIAlertController(title: "Attention!", message: "Your image will be shown to all users of the app! Please be considerate. Upload an image of the penny machine, not just an image of a coin. With the upload, you grant the PennyMe team the unrestricted right to process, alter, share, distribute and publicly expose this image.", preferredStyle: .alert)

// Create the OK action
let okAction = UIAlertAction(title: "OK", style: .default) { (_) in
Expand Down
2 changes: 1 addition & 1 deletion PennyMe/VersionManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class VersionManager {

func showVersionInfoAlertIfNeeded() {
if shouldShowVersionInfo() {
let alert = UIAlertController(title: "PennyMe v\(currentVersion ?? "")", message: "Add new machine (BUGFIX)! \n This version allows you to submit a request to add a new machine to the map. Simply press longer on the map, input some information, upload a picture as a “proof” and complete the PennyMe database with your contributions!\n In addition, search results are now colored based on machine status.", preferredStyle: .alert)
let alert = UIAlertController(title: "PennyMe v\(currentVersion ?? "")", message: "This version includes various small usability improvements. Pop-ups should be more clear now. When you create a new machine (via long-tap on the map) the pop-ups are more informative.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
UIApplication.shared.windows.first?.rootViewController?.present(alert, animated: true, completion: nil)
}
Expand Down
2 changes: 1 addition & 1 deletion PennyMe/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -499,7 +499,7 @@ extension ViewController: MKMapViewDelegate {
guard let annotation = (sender.view as? MKAnnotationView)?.annotation else {return}
// first option: it's a new machine pin - present form
if let newmachine = annotation as? NewMachine {
if #available(iOS 13.0, *) {
if #available(iOS 14.0, *) {
let swiftUIViewController = UIHostingController(rootView: RequestFormView(coordinate: newmachine.coordinate)
)
present(swiftUIViewController, animated: true, completion: removeNewMachinePin)
Expand Down
Loading

0 comments on commit 85b1ee5

Please sign in to comment.