Skip to content

Commit

Permalink
search bar añadida y notificaciones locales
Browse files Browse the repository at this point in the history
  • Loading branch information
MiguelFerrer99 committed Feb 1, 2021
1 parent 594eac0 commit 7091954
Show file tree
Hide file tree
Showing 12 changed files with 165 additions and 15 deletions.
6 changes: 5 additions & 1 deletion MVVM.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
A26DD00625C620DB00F668E5 /* FetchUsers.swift in Sources */ = {isa = PBXBuildFile; fileRef = A26DD00525C620DB00F668E5 /* FetchUsers.swift */; };
A26DD00E25C626A600F668E5 /* CardView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A26DD00D25C626A600F668E5 /* CardView.swift */; };
A26DD01125C637CD00F668E5 /* UserView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A26DD01025C637CD00F668E5 /* UserView.swift */; };
A2A548B325C7E6A4007BDD58 /* SearchBar.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2A548B225C7E6A4007BDD58 /* SearchBar.swift */; };
/* End PBXBuildFile section */

/* Begin PBXFileReference section */
Expand All @@ -32,6 +33,7 @@
A26DD00525C620DB00F668E5 /* FetchUsers.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchUsers.swift; sourceTree = "<group>"; };
A26DD00D25C626A600F668E5 /* CardView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CardView.swift; sourceTree = "<group>"; };
A26DD01025C637CD00F668E5 /* UserView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UserView.swift; sourceTree = "<group>"; };
A2A548B225C7E6A4007BDD58 /* SearchBar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SearchBar.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */

/* Begin PBXFrameworksBuildPhase section */
Expand Down Expand Up @@ -96,9 +98,10 @@
A26DD00025C620BB00F668E5 /* View */ = {
isa = PBXGroup;
children = (
A26DD01025C637CD00F668E5 /* UserView.swift */,
A26DCFEE25C620A200F668E5 /* ContentView.swift */,
A26DD00D25C626A600F668E5 /* CardView.swift */,
A26DD01025C637CD00F668E5 /* UserView.swift */,
A2A548B225C7E6A4007BDD58 /* SearchBar.swift */,
);
path = View;
sourceTree = "<group>";
Expand Down Expand Up @@ -186,6 +189,7 @@
A26DCFEB25C620A200F668E5 /* AppDelegate.swift in Sources */,
A26DD01125C637CD00F668E5 /* UserView.swift in Sources */,
A26DD00625C620DB00F668E5 /* FetchUsers.swift in Sources */,
A2A548B325C7E6A4007BDD58 /* SearchBar.swift in Sources */,
A26DCFED25C620A200F668E5 /* SceneDelegate.swift in Sources */,
A26DCFEF25C620A200F668E5 /* ContentView.swift in Sources */,
);
Expand Down
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Bucket
uuid = "1E3F7161-B6F1-4B62-9FEC-6C9912399FA2"
type = "1"
version = "2.0">
</Bucket>
10 changes: 9 additions & 1 deletion MVVM/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,25 @@
//

import UIKit
import UserNotifications

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {



func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
UNUserNotificationCenter.current().delegate = self
return true
}

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
if response.actionIdentifier == "buttonID" {
NotificationCenter.default.post(name: NSNotification.Name("goUserView"), object: nil)
}
}

// MARK: UISceneSession Lifecycle

func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
Expand Down
21 changes: 21 additions & 0 deletions MVVM/Assets.xcassets/swift.imageset/Contents.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"images" : [
{
"filename" : "swift.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file added MVVM/Assets.xcassets/swift.imageset/swift.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion MVVM/Model/User.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import Foundation

//El modelo es donde estarán las estucturas de datos donde estos se almacenen

struct User: Codable, Identifiable {
struct User: Codable, Identifiable, Hashable {
var id:Int
var firstname:String
var lastname:String
Expand Down
3 changes: 3 additions & 0 deletions MVVM/SceneDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.

//Cuando entramos en la aplicación, desaparencen las notificaciones de esta
UIApplication.shared.applicationIconBadgeNumber = 0
}

func sceneWillResignActive(_ scene: UIScene) {
Expand Down
27 changes: 17 additions & 10 deletions MVVM/View/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,29 +11,36 @@ import SwiftUI

struct ContentView: View {

@ObservedObject var users = FetchUsers()
@State var showUser = false
@ObservedObject var fetchedUsers = FetchUsers()
@State private var searchText = ""
@State private var showUserView = false
@State private var heightView:CGFloat = 0

var body: some View {

NavigationView {
ScrollView {
VStack {
//Card View de cada usuario
ForEach(self.users.users) { user in
SearchBar(text: self.$searchText)
ForEach(self.fetchedUsers.users.filter {
searchText.isEmpty ? true : $0.firstname.lowercased().prefix(searchText.count).localizedStandardContains(searchText)
}, id: \.self) { user in
NavigationLink(
destination: UserView(userDetails: user),
isActive: self.$showUser,
isActive: self.$showUserView,
label: {
CardView(userDetails: user)
})
})
}
}
}.onAppear {
//Fetching users...
self.users.fetchUsers()
}
.navigationBarTitle("Users")
}.onAppear {
self.fetchedUsers.fetchUsers()
//When action notification button is pressed...
NotificationCenter.default.addObserver(forName: NSNotification.Name("goUserView"), object: nil, queue: .main) { (_) in
//codigo para hacer cuando se pulse el boton ir a UserView
showUserView.toggle()
}
}
}
}
Expand Down
54 changes: 54 additions & 0 deletions MVVM/View/SearchBar.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
//
// SearchBar.swift
// MVVM
//
// Created by Miguel Ferrer Fornali on 1/2/21.
//

import SwiftUI

struct SearchBar: View {

@Binding var text: String
@State private var isEditing = false

var body: some View {
HStack {
TextField("Search ...", text: $text)
.padding(7)
.padding(.horizontal, 25)
.background(Color(.systemGray6))
.cornerRadius(8)
.disableAutocorrection(true)
.overlay(
HStack {
Image(systemName: "magnifyingglass")
.foregroundColor(.gray)
.frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
.padding(.leading, 8)

if isEditing && !text.isEmpty {
Button(action: {
self.text = ""

}) {
Image(systemName: "multiply.circle.fill")
.foregroundColor(.gray)
.padding(.trailing, 8)
}
}
}
)
.padding(.horizontal, 10)
.onTapGesture {
self.isEditing = true
}
}
}
}

struct SearchBar_Previews: PreviewProvider {
static var previews: some View {
SearchBar(text: .constant(""))
}
}
48 changes: 48 additions & 0 deletions MVVM/View/UserView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
//

import SwiftUI
import UserNotifications

struct UserView: View {

Expand All @@ -23,11 +24,58 @@ struct UserView: View {
Text(userDetails.email)
.font(.title3)
.foregroundColor(.gray)
Button {
localNotification()
} label: {
Text("Notify me")
.padding()
.background(Color.blue)
.cornerRadius(10)
.foregroundColor(.black)
.font(.title3)
}
}
Spacer()
.navigationBarTitle(userDetails.firstname)
}
}

func localNotification() {

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (_, _) in

}

//Content
let content = UNMutableNotificationContent()
content.title = "MVVM notification"
content.body = "\(userDetails.firstname) \(userDetails.lastname) has notified"
content.sound = UNNotificationSound.defaultCritical
content.badge = 1

//Image (en el caso que queramos añadir una imagen)
if let path = Bundle.main.path(forResource: "swift", ofType: "png", inDirectory: "Assets.xcasssets") {
let url = URL(fileURLWithPath: path)
do {
let image = try UNNotificationAttachment(identifier: "imageID", url: url, options: nil)
content.attachments = [image]
} catch {
print("No cargó la imagen")
}
}

//Buttons
let button = UNNotificationAction(identifier: "buttonID", title: "Open \(userDetails.firstname) View", options: .foreground)
let cancel = UNNotificationAction(identifier: "cancelID", title: "Cancel", options: .destructive)
let category = UNNotificationCategory(identifier: "categoryID", actions: [button,cancel], intentIdentifiers: [])
UNUserNotificationCenter.current().setNotificationCategories([category])
content.categoryIdentifier = "categoryID"

//Trigger (Disparador)
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: "notificationRequestID", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
}

struct UserView_Previews: PreviewProvider {
Expand Down
3 changes: 1 addition & 2 deletions MVVM/ViewModel/FetchUsers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ class FetchUsers: ObservableObject {

@Published var users:[User] = []
let url = "https://raw.githubusercontent.com/MiguelFerrer99/MVVMexample/main/users.json"
let url2 = "https://jsonplaceholder.typicode.com/users"

func fetchUsers() {

Expand All @@ -23,7 +22,7 @@ class FetchUsers: ObservableObject {
URLSession.shared.dataTask(with: url) { (data, _ ,_) in

let usersDecoder = try! JSONDecoder().decode([User].self, from: data!)

print(usersDecoder)
DispatchQueue.main.async {
self.users = usersDecoder
}
Expand Down

0 comments on commit 7091954

Please sign in to comment.