釣魚術
swift
swiftui
JSON
FileManager
print(url.path)
以便在開發除錯階段找到電腦上的路徑saved
目錄,用來擺放使用者的新儲存檔案let fileUrl = newFolderUrl.appendingPathComponent("NewSecretLocations.json")
則是根據上述生出來的新目錄下,透過 .appendingPathComponent()
方式來產生加上 NewSecretLocations.json
檔名的 urlself.encodeCoordinate()
則是我另外寫的一隻轉換函數,用來將 CLLocationCoordinate2D 拆解成 latitude 和 longtitude,請看後面一段。func saveDataToFile()
func saveDataToFile() {
// Create Dir
let manager = FileManager.default
guard let url = manager.urls(for: .documentDirectory, in: .userDomainMask).first else {
return
}
print(url.path)
let newFolderUrl = url.appendingPathComponent("saved")
do {
try manager.createDirectory(at: newFolderUrl, withIntermediateDirectories: true)
} catch {
print(error)
}
// Create file
let fileUrl = newFolderUrl.appendingPathComponent("NewSecretLocations.json")
let jsonEncoder = JSONEncoder()
jsonEncoder.outputFormatting = .prettyPrinted
// 需要做 error handling
do {
let jsonData = try jsonEncoder.encode(self.encodeCoordinate())
if let jsonString = String(data: jsonData, encoding: .utf8) {
print(jsonString)
//try jsonData.write(to: myLocationFile)
manager.createFile(atPath: fileUrl.path,
contents: jsonData,
attributes: [FileAttributeKey.creationDate: Date()])
}
} catch {
print(error)
}
}
func transferCoordinate()
func transferCoordinate() { // 將目前程式使用中的圖釘清單內新增轉換後的資料
for pin in self.originLoadData {
self.locationData.append(
PinLocation(
name: pin.name,
image: pin.image,
coordinate: CLLocationCoordinate2D(latitude: pin.latitude, longitude: pin.longitude),
rank: pin.rank)
)
}
}
func encodeCoordinate() -> [FishPinAnnotation]
func encodeCoordinate() -> [FishPinAnnotation] {
var retPins: [FishPinAnnotation] = []
for pin in self.locationData {
retPins.append(
FishPinAnnotation(
name: pin.name,
image: pin.image,
latitude: pin.coordinate.latitude,
longitude: pin.coordinate.longitude,
rank: pin.rank)
)
}
return retPins
}