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

版本记录

版本号 时间
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的高级功能,感兴趣的给个赞或者关注~~~

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,539评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,594评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,871评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,963评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,984评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,763评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,468评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,357评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,850评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,002评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,144评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,823评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,483评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,026评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,150评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,415评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,092评论 2 355

推荐阅读更多精彩内容