Skip to content

Commit

Permalink
feat: transfer images from phone to watch
Browse files Browse the repository at this point in the history
  • Loading branch information
jhrcook committed Aug 25, 2020
1 parent 8a6f5c1 commit 240e2c6
Show file tree
Hide file tree
Showing 9 changed files with 65 additions and 18 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ See the [Projects](https://github.com/jhrcook/WaterMe/projects/1) tab to view th

### Companion Watch app

<img width="300px" src="demos/waterme-watch-ui.gif">
<img height="220px" src="demos/waterme-watch-ui.gif">
<img height="220px" src="demos/waterme-watch-image.png">

### Can water a plant from the watch

Expand Down
8 changes: 4 additions & 4 deletions WaterMe/Mainviews/MakeNewPlantView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ struct MakeNewPlantView: View {

@State private var userSelectedImage: UIImage?

var watchCommunicator: PhoneToWatchCommunicator?
var watchCommunicator: PhoneToWatchCommunicator

var body: some View {
NavigationView {
Expand Down Expand Up @@ -86,18 +86,18 @@ struct MakeNewPlantView: View {
var newPlant = Plant(name: plantName, datesWatered: datesWatered)
if let uiImage = userSelectedImage {
newPlant.savePlantImage(uiImage: uiImage)
watchCommunicator?.transferImageToWatch(newPlant) // Currently, doesn't do anything.
}

garden.plants.append(newPlant)
watchCommunicator?.addToWatch(newPlant)
watchCommunicator.addToWatch(newPlant)
watchCommunicator.transferImageToWatch(newPlant, andSendUpdatedPlant: false)
presentationMode.wrappedValue.dismiss()
}

}

struct MakeNewPlantView_Previews: PreviewProvider {
static var previews: some View {
MakeNewPlantView(garden: Garden())
MakeNewPlantView(garden: Garden(), watchCommunicator: PhoneToWatchCommunicator())
}
}
4 changes: 3 additions & 1 deletion WaterMe/Mainviews/PlantDetailView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,9 @@ struct PlantDetailView: View {
.onAppear() {
self.watchCommunicator.gardenDelegate = self
}
.onDisappear() {
self.watchCommunicator.transferImageToWatch(self.plant)
}
}


Expand All @@ -266,7 +269,6 @@ struct PlantDetailView: View {
if let uiImage = userSelectedImage {
image = Image(uiImage: uiImage)
plant.savePlantImage(uiImage: uiImage)
watchCommunicator.transferImageToWatch(plant) // Currently, does not do anything.
}
updatePlant()
}
Expand Down
31 changes: 26 additions & 5 deletions WaterMe/Watch Connectivity/PhoneToWatchCommunicator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,26 +46,47 @@ extension PhoneToWatchCommunicator {
session.sendMessageOrTransfer(info: info)
}


func deleteFromWatch(_ plant: Plant) {
let dm = WCDataManager()
let info = dm.packageMessageInfo(datatype: .deletePlant,
data: [plant.id])
session.sendMessageOrTransfer(info: info)
}


func updateOnWatch(_ plant: Plant) {
let dm = WCDataManager()
let info = dm.packageMessageInfo(datatype: .updatePlant, data: dm.convert(plantForWatch: plant))
session.sendMessageOrTransfer(info: info)
}

func transferImageToWatch(_ plant: Plant) {
// TODO
// transfer file and call `updateOnWatch(plant)` to send new image name
updateOnWatch(plant)
#warning("TO-DO: Image name is updated on watch, but not file is sent.")

func transferImageToWatch(_ plant: Plant, andSendUpdatedPlant sendUpdatedPlant: Bool = true) {
print("Transfering image from plant '\(plant.name)'.")
guard let originalImageName = plant.imageName else { return }

let originalImageURL = getDocumentsDirectory().appendingPathComponent(originalImageName)
do {
print("Copying and resizing image to send to watch.")
let newImageURL = try copyResizeCompressJPEG(url: originalImageURL)
session.transferFile(newImageURL, metadata: [PhoneToWatchDataType.imageFilename.rawValue : originalImageName])
if sendUpdatedPlant { updateOnWatch(plant) }
} catch {
print("error in resizing image: \(error.localizedDescription)")
}
}


func session(_ session: WCSession, didFinish fileTransfer: WCSessionFileTransfer, error: Error?) {
if let error = error {
print("File transfer did finish with error: \(error.localizedDescription)")
} else {
print("File transfer did finish without error.")
}
}


func sendAllDataToWatch(_ garden: Garden) {
let dm = WCDataManager()
let info = dm.packageMessageInfo(datatype: .allData, data: dm.convert(plantsForWatch: garden.plants))
Expand Down
4 changes: 2 additions & 2 deletions WaterMe/Watch Connectivity/WCDataManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ enum PhoneToWatchDataType: String {
case addPlant
case deletePlant
case updatePlant
case imageFile
case imageFilename
case allData
}

Expand Down Expand Up @@ -182,7 +182,7 @@ func copyResizeCompressJPEG(url: URL) throws -> URL {

let imageData = try Data(contentsOf: url)
if let image = UIImage(data: imageData) {
let newImage = image.resized(toWidth: 50)
let newImage = image.resized(toWidth: 150)
if let newData = newImage?.jpegData(compressionQuality: 0.7) {
try newData.write(to: newUrl)
} else {
Expand Down
21 changes: 18 additions & 3 deletions WaterMe/Watch Connectivity/WatchToPhoneCommunicator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ extension WatchToPhoneCommunicator {
deletePlants(plantIds: info[DataDictionaryKey.data.rawValue] as? [String] ?? [String]())
case .updatePlant:
updatePlant(plantInfo: info[DataDictionaryKey.data.rawValue] as? [String : Any] ?? [String : Any]())
case .imageFile, .allData:
case .imageFilename, .allData:
throw WatchConnectivityDataError.inappropriateDataType(dataType.rawValue)
}
} else {
Expand All @@ -94,7 +94,6 @@ extension WatchToPhoneCommunicator {
} else {
throw WatchConnectivityDataError.noDataTypeIndicated
}

}


Expand Down Expand Up @@ -126,7 +125,23 @@ extension WatchToPhoneCommunicator {


func session(_ session: WCSession, didReceive file: WCSessionFile) {
#warning("TO-DO: File recieved but not parsed.")
print("Recieved file transfer.")
if let metadata = file.metadata {
if let plantImageName = metadata[PhoneToWatchDataType.imageFilename.rawValue] as? String {
print("Updating plant and transfering file.")
let newURL = getDocumentsDirectory().appendingPathComponent(plantImageName)
do {
try FileManager().copyItem(at: file.fileURL, to: newURL)
} catch {
print("Unable to copy transfered file: \(error.localizedDescription)")
}
updateGardenDelegateInForeground()
} else {
print("Unable to access file name in meta data.")
}
} else {
print("No file meta data with transfered file.")
}
}


Expand Down
8 changes: 8 additions & 0 deletions WaterMeWatchApp Extension/Models/GardenWatch.swift
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,15 @@ class GardenWatch: ObservableObject {

func update(_ plant: PlantWatch, addIfNew: Bool = true, updatePlantOrder: Bool = true) {
if let idx = plants.firstIndex(where: { $0.id == plant.id }) {

// Check if the new plant has a different image file.
let oldPlant = plants[idx]
if oldPlant.imageName != plant.imageName {
oldPlant.deletePlantImageFile()
}

plants[idx] = plant

} else if addIfNew {
plants.append(plant)
}
Expand Down
4 changes: 2 additions & 2 deletions WaterMeWatchApp Extension/Views/PlantRowView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -109,9 +109,9 @@ struct PlantRowView: View {
ZStack {
self.plant.loadPlantImage()
.resizable()
.scaledToFit()
.scaledToFill()
.frame(width: 65, height: 65)
.clipShape(Circle())
.frame(width: 65)
VStack {
Spacer()
HStack {
Expand Down
Binary file added demos/waterme-watch-image.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 240e2c6

Please sign in to comment.