我正在使用Swift 3构建一个APP并且无后端,我无法从我的APP上传图像(用户将从相机或照片库中拍摄照片)到后端。 APP正在将图像保存到photoLibrary:
func savePic() {
let imageData = UIImageJPEGRepresentation(itemPic.image!, 0.5);
let compressedJPEGImage = UIImage(data: imageData!);
UIImageWriteToSavedPhotosAlbum(compressedJPEGImage!, nil, nil, nil);
}
拍摄的图像地址是什么?
我如何将其上传到backEndLess?
答案 0 :(得分:3)
您应该使用Backendless.file.upload
方法。
例如:
func uploadImage(_ img:UIImage){
//convert UIImage to jpg Data with 0.5 compressionQuality (use 1 for full quality)
let jpg=UIImageJPEGRepresentation(img, 0.5);
//saving file name with current timestamp
let fileName="IMG_\(Date().timeIntervalSince1970).jpg";
//uploading image asynchronously
Backendless.sharedInstance().file.upload("imagesFolder/\(fileName)", content:jpg, response: {(res) in
//uploading image finished
}, error: {(e) in
//failed to upload
print("error code: \(e!.faultCode)");
})
}
如果您需要以PNG
格式上传,请使用UIImagePNGRepresentation
代替IImageJPEGRepresentation
要上传用户从已保存的相册中直接拍摄的图像或通过相机拍摄,您可以这样做:
UINavigationControllerDelegate
& UIImagePickerControllerDelegate
UIImagePickerControllerSourceType
,例如:.photoLibrary
,.camera
或.savedPhotosAlbum
didFinishPickingMediaWithInfo
这是一个例子:
class MyViewController : UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate{
var imgPicker = UIImagePickerController();
var backendless = Backendless.sharedInstance();
override func viewDidLoad() {
imgPicker.delegate = self;
}
@IBAction func imgFromCamera(_ btn:UIButton){
imgPicker.sourceType = .camera;//image picker with camera
show(imgPicker, sender: self);//open image picker
}
@IBAction func imgFromSavedPhotos(_ btn:UIButton){
imgPicker.sourceType = .savedPhotosAlbum;//image picker from saved photos
show(imgPicker, sender: self);//open image picker
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let img = info[UIImagePickerControllerOriginalImage] as! UIImage;
uploadImage(img);
dismiss(animated: true, completion: nil);
}
func uploadImage(_ img:UIImage){
let jpg=UIImageJPEGRepresentation(img, 1);//full scale JPG
//let png=UIImagePNGRepresentation(img);//full scale PNG
let fileName="IMG_\(Date().timeIntervalSince1970).jpg";
//upload img
Backendless.sharedInstance().file.upload("imagesFolder/\(fileName)", content:jpg, response: {(res) in
//successfully uploaded
}, error: {(e) in
//failed to upload
})
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: false, completion: {
print("user didn't pick any image");
});
}
}
另请注意,要使用您应声明的内容:NSPhotoLibraryUsageDescription&您Info.plist
中的NSCameraUsageDescription,否则会在iOS 10
中崩溃,如链接参考中所述。
这是一个例子:
<key>NSPhotoLibraryUsageDescription</key>
<string>Your explanation here</string>
<key>NSCameraUsageDescription</key>
<string>Your explanation here</string>