iOS开发 swift -- 获取相册相机

一 代理

swift一定要遵循UIImagePickerControllerDelegate,UINavigationControllerDelegate俩个代理

二 info.plist

    在info.plist中加入安全域名白名单(右键info.plist用source code打开)
    NSCameraUsageDescription
    访问相机
    NSPhotoLibraryUsageDescription
    访问相册

三 代码示例

func addIcon()  {
        
        let alertAction = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)
        alertAction.addAction(UIAlertAction.init(title: "获取相机", style: .default, handler: { (alertCamera) in
            
            let picker:UIImagePickerController = UIImagePickerController()
            picker.delegate = self as UIImagePickerControllerDelegate & UINavigationControllerDelegate
            picker.sourceType = .camera
            picker.allowsEditing = true
            if UIImagePickerController.isSourceTypeAvailable(.camera){

                self.present(picker, animated: true, completion: { () -> Void in
                    
                })
            }else{
                MBProgressHUD.showForError(to: self.view, text: "为授予防问相机权限", completion: nil)
            }
        }))
        
        alertAction.addAction(UIAlertAction.init(title: "获取相册", style:.default, handler: { (alertPhpto) in
            
            let picker:UIImagePickerController = UIImagePickerController()
            picker.delegate = self as UIImagePickerControllerDelegate & UINavigationControllerDelegate
            picker.sourceType = .photoLibrary
            picker.allowsEditing = true
            
            if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){

                self.present(picker, animated: true, completion: {
                    () -> Void in
                })
            }else{
                MBProgressHUD.showForError(to: self.view, text: "为授予防问相册权限", completion: nil)
            }
        }))
        
        alertAction.addAction(UIAlertAction.init(title: "取消", style: .cancel, handler: { (alertCancel) in
            
        }))
        
        self.present(alertAction, animated: true, completion: nil)
    }

    // MARK: ImagePicker Delegate 选择图片成功后代理
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        if let chosenImage =  info[UIImagePickerControllerOriginalImage] as? UIImage {
            picker.dismiss(animated: true) {
                self.iconImage.image = chosenImage
            }
        //处理传入后台
        }
    }

四 上传到后台

    /// 上传图片
    ///
    /// - Parameters:
    ///   - path: <#path description#>
    ///   - image: <#image description#>
    ///   - completion: <#completion description#>
    class func uploadImage(path: String, image: UIImage, completion: @escaping (_ succeeded: Bool, _ url: String?) -> Void) {

        /* 签名 可忽略
        let timestamp  = String(Int(NSDate().timeIntervalSince1970 * 1000))
        var _paramters = [String: Any]()
        _paramters["timestamp"] = timestamp
        let sortedKeys = _paramters.keys.sorted()
        var temp = sortedKeys.map({ "\($0)=\(_paramters[$0]!)" }).joined(separator: "&")
        temp += "&--------"
        let sign = temp.md5().uppercased()
        _paramters["sign"] = sign
        */
        
        Alamofire.upload(multipartFormData: { (multipartFormData) in
            let data = UIImageJPEGRepresentation(image, 0.9)
            multipartFormData.append(data!, withName: "file", fileName: "image.png", mimeType: "image/png")
            
            for (key, value) in _paramters {
                multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
            }
        }, to: Constant.baseURL + path) { (result) in
            switch result {
            case .success(let upload, _, _):
                upload.responseJSON(completionHandler: { (response) in
                    completion(true, JSON(response.data!)["data"].string)
                })
            case .failure(let error):
                print(error)
                completion(false, nil)
            }
        }
    }

如有不妥,请多多指教

你可能感兴趣的:(iOS开发 swift -- 获取相册相机)