程序調(diào)試 (三) —— Xcode Simulator的高級功能(二)

版本記錄

版本號(hào) 時(shí)間
V1.0 2021.01.05 星期二

前言

程序總會(huì)有bug忘古,如果有好的調(diào)試技巧和方法苍息,那么就是事半功倍源譬,這個(gè)專題專門和大家分享下和調(diào)試相關(guān)的技巧集惋。希望可以幫助到大家。感興趣的可以看下面幾篇文章踩娘。
1. 程序調(diào)試 (一) —— App Crash的調(diào)試和解決示例(一)
2. 程序調(diào)試 (二) —— 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的高級功能刮刑,感興趣的給個(gè)贊或者關(guān)注~~~

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市养渴,隨后出現(xiàn)的幾起案子闰集,更是在濱河造成了極大的恐慌腐螟,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,968評論 6 482
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異虱疏,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)翔试,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,601評論 2 382
  • 文/潘曉璐 我一進(jìn)店門爆土,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人宇立,你說我怎么就攤上這事踪宠。” “怎么了妈嘹?”我有些...
    開封第一講書人閱讀 153,220評論 0 344
  • 文/不壞的土叔 我叫張陵柳琢,是天一觀的道長。 經(jīng)常有香客問我,道長柬脸,這世上最難降的妖魔是什么他去? 我笑而不...
    開封第一講書人閱讀 55,416評論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮倒堕,結(jié)果婚禮上灾测,老公的妹妹穿的比我還像新娘。我一直安慰自己涩馆,他們只是感情好行施,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,425評論 5 374
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著魂那,像睡著了一般蛾号。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上涯雅,一...
    開封第一講書人閱讀 49,144評論 1 285
  • 那天鲜结,我揣著相機(jī)與錄音,去河邊找鬼活逆。 笑死精刷,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的蔗候。 我是一名探鬼主播怒允,決...
    沈念sama閱讀 38,432評論 3 401
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼锈遥!你這毒婦竟也來了纫事?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,088評論 0 261
  • 序言:老撾萬榮一對情侶失蹤所灸,失蹤者是張志新(化名)和其女友劉穎丽惶,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體爬立,經(jīng)...
    沈念sama閱讀 43,586評論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡钾唬,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,028評論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了侠驯。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片抡秆。...
    茶點(diǎn)故事閱讀 38,137評論 1 334
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖吟策,靈堂內(nèi)的尸體忽然破棺而出琅轧,到底是詐尸還是另有隱情,我是刑警寧澤踊挠,帶...
    沈念sama閱讀 33,783評論 4 324
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響效床,放射性物質(zhì)發(fā)生泄漏睹酌。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,343評論 3 307
  • 文/蒙蒙 一剩檀、第九天 我趴在偏房一處隱蔽的房頂上張望憋沿。 院中可真熱鬧,春花似錦沪猴、人聲如沸辐啄。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,333評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽壶辜。三九已至,卻和暖如春担租,著一層夾襖步出監(jiān)牢的瞬間砸民,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,559評論 1 262
  • 我被黑心中介騙來泰國打工奋救, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留岭参,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,595評論 2 355
  • 正文 我出身青樓尝艘,卻偏偏與公主長得像演侯,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子背亥,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,901評論 2 345

推薦閱讀更多精彩內(nèi)容