美文网首页
程序调试 (三) —— Xcode Simulator的高级功能

程序调试 (三) —— Xcode Simulator的高级功能

作者: 刀客传奇 | 来源:发表于2021-01-05 09:05 被阅读0次

    版本记录

    版本号 时间
    V1.0 2021.01.05 星期二

    前言

    程序总会有bug,如果有好的调试技巧和方法,那么就是事半功倍,这个专题专门和大家分享下和调试相关的技巧。希望可以帮助到大家。感兴趣的可以看下面几篇文章。
    1. 程序调试 (一) —— App Crash的调试和解决示例(一)
    2. 程序调试 (二) —— Xcode Simulator的高级功能(一)

    源码

    1. Swift

    首先看下工程组织目录:

    下面就是源码啦

    1. AppMain.swift
    
    import SwiftUI
    
    @main
    struct AppMain: App {
      var body: some Scene {
        WindowGroup {
          ContentView()
        }
      }
    }
    
    2. ContentView.swift
    
    import SwiftUI
    import UserNotifications
    
    struct ContentView: View {
      let places = WondersOfTheWorld().places
      @State var shakeDetected = false
      @State var memoryWarningDetected = false
    
      var body: some View {
        ZStack {
          EventViewRepresentable()
          TabView {
            VStack {
              HStack {
                Spacer()
                Button(
                  action: {
                    UNUserNotificationCenter.current()
                      .requestAuthorization(options: [.alert, .sound, .badge]) {granted, _  in
                        print("Notification permission granted: \(granted)")
                      }
                  }, label: {
                    Image(systemName: "bell")
                  })
                  .padding(.trailing)
              }
              PhotoGrid(places: places)
            }
            .tabItem {
              Image(systemName: "photo")
              Text("Photo")
            }
            .tag(0)
            .alert(isPresented: $shakeDetected) {
              Alert(
                title: Text("Shake Detected"),
                message: Text("Submit feedback!"),
                dismissButton: .default(Text("Ok")))
            }
            MapView(location: places.randomElement() ?? places[0], places: places)
              .tabItem {
                Image(systemName: "map")
                Text("Map")
              }
              .tag(1)
          }
          .ignoresSafeArea()
        }
        .alert(isPresented: $memoryWarningDetected) {
          Alert(
            title: Text("Memory Warning Triggered"),
            message: Text("Handle memory warning!"),
            dismissButton: .default(Text("Ok")))
        }
        .onReceive(shakePublisher) { _ in
          print("Received Shake")
          shakeDetected = true
        }
        .onReceive(memoryWarningPublisher) { _ in
          print("Received Memory Warning")
          memoryWarningDetected = true
        }
      }
    }
    
    struct ContentView_Previews: PreviewProvider {
      static var previews: some View {
        Group {
          ContentView()
        }
      }
    }
    
    3. MapView.swift
    
    import SwiftUI
    import MapKit
    
    struct MapView: View {
      let location: Place
      let places: [Place]
      @State var defaultRegion: MKCoordinateRegion
      @StateObject var locationManager = LocationManager()
      @State var trackingMode: MapUserTrackingMode
    
      init(location: Place, places: [Place]) {
        self.location = location
        self.places = places
        _defaultRegion = State(initialValue: location.region)
        _trackingMode = State(initialValue: .follow)
      }
    
      var body: some View {
        ZStack {
          Map(
            coordinateRegion: $locationManager.region,
            interactionModes: [.all],
            showsUserLocation: true,
            userTrackingMode: $trackingMode,
            annotationItems: places) { place in
            MapAnnotation(coordinate: place.location.coordinate) {
              VStack {
                Image(place.image)
                  .resizable()
                  .frame(width: 50, height: 50)
                  .mask(Circle())
                Text(place.name)
              }
            }
          }
          .ignoresSafeArea()
    
          VStack {
            Button(
              action: {
                locationManager.requestAuthorization()
              },
              label: {
                Text("Start Location Services")
              })
              .opacity(locationManager.authorized ? 0 : 1)
            Spacer()
          }
        }
      }
    }
    
    struct MapView_Previews: PreviewProvider {
      static var previews: some View {
        let places = WondersOfTheWorld().places
        MapView(location: places.randomElement() ?? places[0], places: places)
      }
    }
    
    4. EventDetectViewController.swift
    
    import SwiftUI
    import Combine
    
    let shakePublisher = PassthroughSubject<Void, Never>()
    let memoryWarningPublisher = PassthroughSubject<Void, Never>()
    
    class EventDetectViewController: UIViewController {
      override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(
          self,
          selector: #selector(memoryWarning),
          name: UIApplication.didReceiveMemoryWarningNotification,
          object: nil)
      }
    
      @objc private func memoryWarning() {
        memoryWarningPublisher.send()
      }
    }
    
    struct EventViewRepresentable: UIViewControllerRepresentable {
      func makeUIViewController(context: Context) -> EventDetectViewController {
        EventDetectViewController()
      }
    
      func updateUIViewController(_ uiViewController: EventDetectViewController, context: Context) {
        //Do nothing
      }
    }
    
    // MARK: - UIWindow Extension
    extension UIWindow {
      open override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
        super.motionEnded(motion, with: event)
        shakePublisher.send()
      }
    }
    
    5. PhotoGrid.swift
    
    import SwiftUI
    
    struct PhotoGrid: View {
      @State private var selectedPlace: Place?
      let places: [Place]
      let columns = [GridItem()]
    
      var body: some View {
        ScrollView {
          LazyVGrid(columns: columns, alignment: .center, spacing: 10) {
            ForEach(0..<places.count) { index in
              ZStack {
                Button(
                  action: {
                    selectedPlace = places[index]
                  },
                  label: {
                    Image(places[index].image)
                      .resizable()
                      .scaledToFit()
                      .overlay(OverlayContent(title: places[index].name), alignment: .bottom)
                  })
              }
            }
          }
        }
        .sheet(item: $selectedPlace) { item in
          DetailView(place: item)
        }
      }
    }
    
    struct OverlayContent: View {
      let title: String
    
      var body: some View {
        Text(title)
          .font(.title)
          .fontWeight(.regular)
          .frame(maxWidth: .infinity)
          .foregroundColor(Color.black)
          .background(Color.white)
          .opacity(0.7)
      }
    }
    
    struct DetailView: View {
      let place: Place
    
      var body: some View {
        GeometryReader { geo in
          ZStack {
            Image(place.image)
              .resizable()
              .scaledToFill()
              .frame(width: geo.size.width, height: geo.size.height)
              .opacity(0.2)
            Text(place.details)
              .font(.body)
              .fontWeight(.semibold)
              .multilineTextAlignment(.center)
              .padding(.horizontal, 10.0)
          }
          .ignoresSafeArea()
        }
      }
    }
    
    struct PhotoGrid_Previews: PreviewProvider {
      static var previews: some View {
        let places = WondersOfTheWorld().places
        PhotoGrid(places: places)
      }
    }
    
    6. LocationManager.swift
    
    import CoreLocation
    import MapKit
    
    final class LocationManager: NSObject, ObservableObject {
      var locationManager = CLLocationManager()
      @Published var region: MKCoordinateRegion
      @Published var authorized = false
    
      override init() {
        let place = WondersOfTheWorld().places.randomElement() ?? WondersOfTheWorld().places[0]
        region = MKCoordinateRegion(center: place.location.coordinate, latitudinalMeters: 1000, longitudinalMeters: 1000)
        super.init()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        if locationManager.authorizationStatus == .authorizedWhenInUse {
          authorized = true
          locationManager.startUpdatingLocation()
        }
      }
    
      func requestAuthorization() {
        locationManager.requestWhenInUseAuthorization()
      }
    }
    
    // MARK: - CLLocationManagerDelegate
    extension LocationManager: CLLocationManagerDelegate {
      func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        if locationManager.authorizationStatus == .authorizedWhenInUse {
          authorized = true
          locationManager.startUpdatingLocation()
        }
      }
    
      func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let latest = locations.first else {
          return
        }
        region = MKCoordinateRegion.init(center: latest.coordinate, latitudinalMeters: 1000, longitudinalMeters: 1000)
        print("Region: \(region)")
      }
    
      func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        guard let clError = error as? CLError else {
          return
        }
        switch clError {
        case CLError.denied:
          print("Access denied")
        default:
          print("LocationManager didFailWithError: \(clError.localizedDescription)")
        }
      }
    }
    
    7. places.json
    
    [
      {
        "name": "Taj Mahal",
        "latitude": 27.1751496,
        "longitude": 78.0399535,
        "image": "tajMahal",
        "details": "From Wikipedia: The Taj Mahal is an ivory-white marble mausoleum on the southern bank of the river Yamuna in the Indian city of Agra. It was commissioned in 1632 by the Mughal emperor Shah Jahan (reigned from 1628 to 1658) to house the tomb of his favourite wife, Mumtaz Mahal; it also houses the tomb of Shah Jahan himself. The tomb is the centrepiece of a 17-hectare (42-acre) complex, which includes a mosque and a guest house, and is set in formal gardens bounded on three sides by a crenellated wall."
      },
      {
        "name": "Petra",
        "latitude": 30.339796,
        "longitude": 35.4355013,
        "image": "petra",
        "details": "From Wikipedia: Petra originally known to its inhabitants in Nabataean Aramaic as Raqēmō, is a historical and archaeological city in southern Jordan. Petra lies around Jabal Al-Madbah in a basin surrounded by mountains which form the eastern flank of the Arabah valley that runs from the Dead Sea to the Gulf of Aqaba.The area around Petra has been inhabited from as early as 7000 BC, and the Nabataeans might have settled in what would become the capital city of their kingdom, as early as the 4th century BC. However, archaeological work has only discovered evidence of Nabataean presence dating back to the second century BC by which time Petra had become their capital."
      },
      {
        "name": "Christ the Redeemer",
        "latitude": -22.951911,
        "longitude": -43.2126759,
        "image": "christTheRedeemer",
        "details": "From Wikipedia: Christ the Redeemer is an Art Deco statue of Jesus Christ in Rio de Janeiro, Brazil, created by French sculptor Paul Landowski and built by Brazilian engineer Heitor da Silva Costa, in collaboration with French engineer Albert Caquot. Romanian sculptor Gheorghe Leonida fashioned the face. Constructed between 1922 and 1931, the statue is 30 metres (98 ft) high, excluding its 8-metre (26 ft) pedestal. The arms stretch 28 metres (92 ft) wide."
      },
      {
        "name": "Machu Picchu",
        "latitude": -13.163136,
        "longitude": -72.5471516,
        "image": "machuPichu",
        "details": "From Wikipedia: Machu Picchu is a 15th-century Inca citadel, located in the Eastern Cordillera of southern Peru, on a 2,430-metre (7,970 ft) mountain ridge. It is located in the Machupicchu District within Urubamba Province above the Sacred Valley, which is 80 kilometres (50 mi) northwest of Cuzco. The Urubamba River flows past it, cutting through the Cordillera and creating a canyon with a tropical mountain climate."
      },
      {
        "name": "Chichen Itza",
        "latitude": 20.6862974,
        "longitude": -88.5831391,
        "image": "chichenItza",
        "details": "From Wikipedia: Chichen Itza was a large pre-Columbian city built by the Maya people of the Terminal Classic period. The archaeological site is located in Tinúm Municipality, Yucatán State, Mexico. Chichen Itza was a major focal point in the Northern Maya Lowlands from the Late Classic (c. AD 600–900) through the Terminal Classic (c. AD 800–900) and into the early portion of the Postclassic period (c. AD 900–1200). The site exhibits a multitude of architectural styles, reminiscent of styles seen in central Mexico and of the Puuc and Chenes styles of the Northern Maya lowlands."
      },
      {
        "name": "Colosseum",
        "latitude": 41.8902142,
        "longitude": 12.4900422,
        "image": "colloseum",
        "details": "From Wikipedia: The Colosseum, also known as the Flavian Amphitheatre or Colosseo, is an oval amphitheatre in the centre of the city of Rome, Italy. Built of travertine limestone, tuff (volcanic rock), and brick-faced concrete, it was the largest amphitheatre ever built at the time and held 50,000 to 80,000 spectators. The Colosseum is just east of the Roman Forum"
      },
      {
        "name": "Great Pyramid of Giza",
        "latitude": 29.9792391,
        "longitude": 31.1320132,
        "image": "gizaPyramid",
        "details": "From Wikipedia: The Great Pyramid of Giza (also known as the Pyramid of Khufu or the Pyramid of Cheops) is the oldest and largest of the three pyramids in the Giza pyramid complex bordering present-day Giza in Greater Cairo, Egypt. It is the oldest of the Seven Wonders of the Ancient World, and the only one to remain largely intact."
      },
      {
        "name": "Great Wall of China",
        "latitude": 40.4315185,
        "longitude": 116.5685121,
        "image": "greatWallOfChina",
        "sponsored": false,
        "details": "From Wikipedia: The Great Wall of China is the collective name of a series of fortification systems generally built across the historical northern borders of China to protect and consolidate territories of Chinese states and empires against various nomadic groups of the steppe and their polities."
      }
    ]
    
    8. Place.swift
    
    import CoreLocation
    import MapKit
    
    struct Place: Decodable, Identifiable {
      let name: String
      let image: String
      let details: String
      let location: CLLocation
      let regionRadius: CLLocationDistance = 1000
      let region: MKCoordinateRegion
      var id = UUID()
    
      enum CodingKeys: CodingKey {
        case name
        case image
        case details
        case latitude
        case longitude
      }
    
      init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        name = try values.decode(String.self, forKey: .name)
        image = try values.decode(String.self, forKey: .image)
        details = try values.decode(String.self, forKey: .details)
        let latitude = try values.decode(Double.self, forKey: .latitude)
        let longitude = try values.decode(Double.self, forKey: .longitude)
        location = CLLocation(latitude: latitude, longitude: longitude)
        region = MKCoordinateRegion(
          center: location.coordinate,
          latitudinalMeters: regionRadius,
          longitudinalMeters: regionRadius)
      }
    }
    
    9. WondersOfTheWorld.swift
    
    import Foundation
    
    struct WondersOfTheWorld {
      let places: [Place] = {
        guard let placesJson = Bundle.main.url(forResource: "places", withExtension: "json") else {
          fatalError("Unable to load places")
        }
        do {
          let jsonData = try Data(contentsOf: placesJson)
          return try JSONDecoder().decode([Place].self, from: jsonData)
        } catch {
          fatalError("Unable to parse the places json")
        }
      }()
    }
    
    10. RayWondersPushNotification.apns
    
    {
      "Simulator Target Bundle": "com.raywenderlich.RayWonders",
      "aps": {
        "alert": {
          "title": "Hindi language support added!",
          "body": "Checkout RayWonders app in Hindi!"
        }
      }
    }
    

    后记

    本篇主要讲述了Xcode Simulator的高级功能,感兴趣的给个赞或者关注~~~

    相关文章

      网友评论

          本文标题:程序调试 (三) —— Xcode Simulator的高级功能

          本文链接:https://www.haomeiwen.com/subject/ojhpoktx.html