Ios-常用基础整理

使用相册

导入相册库:

import Photos

Plist文件中添加权限:
Ios-常用基础整理_第1张图片

判断权限:

let status = PHPhotoLibrary.authorizationStatus()
if status == PHAuthorizationStatus.authorized {//允许状态
    DLog("requestAuthorization: 已同意授权")
} else if status == PHAuthorizationStatus.denied {//不允许状态,可以弹出一个    alertview提示用户在隐私设置中开启权限
    let url = URL.init(string: UIApplicationOpenSettingsURLString)
    UIApplication.shared.openURL(url!)
    DLog("requestAuthorization: denied")
} else if status == PHAuthorizationStatus.restricted {//此应用程序没有被授权访问,可能是家长控制权限
    DLog("requestAuthorization:restricted")
} else if status == PHAuthorizationStatus.notDetermined {// 未知,第一次申请权限
    DLog("requestAuthorization:notDetermined")
    // 第一次获取权限,会弹出授权弹窗
    PHPhotoLibrary.requestAuthorization { (status) in
        if status == PHAuthorizationStatus.authorized {
        DLog("requestAuthorization: 已同意授权")
        } else if status == PHAuthorizationStatus.denied {
            DLog("requestAuthorization: 未同意授权")
        }
    }
}

判断Facebook/Instagram/Whatsapp是否安装

首先需要在Plist中添加对应的Scheme
Ios-常用基础整理_第2张图片

判断代码:

// Facebook
UIApplication.shared.canOpenURL(URL(string: "fb://")!)
// Instagram
UIApplication.shared.canOpenURL(URL(string: "instagram://app")!)
// Whatsapp
UIApplication.shared.canOpenURL(URL(string: "whatsapp://")!)

分享图片到Instagram

首先需要有相册的权限,因为下边分享的方式需要保存图片到相册:

代码如下:

do {
    try PHPhotoLibrary.shared().performChangesAndWait {
        let image: UIImage = XXX
        let request = PHAssetChangeRequest.creationRequestForAsset(from: image)
        let assetID = request.placeholderForCreatedAsset?.localIdentifier ?? ""
        DLog("assetID: \(assetID)")
        let shareURL = "instagram://library?LocalIdentifier=" + assetID
        if let urlForRedirect = URL(string: shareURL) {
            UIApplication.shared.openURL(urlForRedirect)
        }
    }
} catch let error {
    DLog("error: \(error)")
}

参考文章:https://stackoverflow.com/questions/11393071/how-to-share-an-image-on-instagram-in-ios

你可能感兴趣的:(IOS,IOS基础)