在Swift中保存圖片到相冊

1.OC中的寫法

在OC中,我們需要保存圖片到相冊需要調用這個方法:

void UIImageWriteToSavedPhotosAlbum(UIImage *image, id completionTarget, SEL completionSelector, void *contextInfo);

想來大家也都看過這個方法的頭文件,在頭文件中有這樣一段話

// Adds a photo to the saved photos album.  The optional completionSelector should have the form:
//  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;

意思是:想要將一張照片保存到相冊中,這個可選的完成方法需要按照下面那個方法的格式來定義。
所以,我們在OC中通常都是直接將這個方法拷貝出來,直接實現這個方法,舉個栗子:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UIImageWriteToSavedPhotosAlbum(self.iconView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);

}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {

    if (error) {
        NSLog(@"保存出錯");
        return;
    }
    NSLog(@"保存成功");
}

在上面這個栗子中,我通過手指觸摸事件,將事先定義好的iconView中的圖像保存到相冊中。

而同樣一個栗子,在Swift中應該怎么樣實現呢?

2.swift中的寫法

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    UIImageWriteToSavedPhotosAlbum(iconView.image, self, "image:didFinishSavingWithError:contextInfo:", nil)
}

func image(image: UIImage, didFinishSavingWithError: NSError?, contextInfo: AnyObject) {
    println("---")

    if didFinishSavingWithError != nil {
        println("錯誤")
        return
    }
    println("OK")
}

同樣的栗子,swift中的實現如上,在swift中,我們跳到頭文件會發現是這樣的,

// Adds a photo to the saved photos album.  The optional completionSelector should have the form:
//  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;

還是OC中那一套,蘋果并沒有幫我們寫好swift下的代碼格式應該怎么寫,所以很多人對此應該怎么使用會產生許多的疑惑,其實,就是像上面那樣,將參數一一對應,以swift中函數的寫法寫出來就可以了。
另外補充一點小知識點:
上面的那個方法我們還可以這么寫,

// 提示:參數 空格 參數別名: 類型
func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) {
    println("---")

// if didFinishSavingWithError != nil {
    if error != nil {
        println("錯誤")
        return
    }
    println("OK")
}

類似這樣的格式:(參數 參數別名: 類型)didFinishSavingWithError error: NSError?
在外部調用時,顯示的是didFinishSavingWithError這個參數名
而在內部使用時,顯示的是error這個參數別名,方便我們的使用,也更加類似OC中的寫法。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容