将swift代码移植到objective-C项目

时间:2017-11-29 05:05:21

标签: ios objective-c swift

我想使用最初用Swift编写的Class

以下说明在网上找到我应该:

  1. 将swift代码添加到目标
  2. #import "projectName-swift.h"文件中添加.m标题,我想使用swift中定义的类。
  3. 在这之后我尝试使用swift Code定义的类,如下所示:

      JPEG *jpeg = nil;
    

    但编译器会强调Use of undeclared identifier 'JPEG'

    以下是发生的事情:

    enter image description here

    这是JPEG类:

    import Foundation
    import MobileCoreServices
    import ImageIO
    
    class JPEG {
        fileprivate let kFigAppleMakerNote_AssetIdentifier = "17"
        fileprivate let path : String
    
        init(path : String) {
            self.path = path
        }
    
        func read() -> String? {
            guard let makerNote = metadata()?.object(forKey: kCGImagePropertyMakerAppleDictionary) as! NSDictionary? else {
                return nil
            }
            return makerNote.object(forKey: kFigAppleMakerNote_AssetIdentifier) as! String?
        }
    
        func write(_ dest : String, assetIdentifier : String) {
            guard let dest = CGImageDestinationCreateWithURL(URL(fileURLWithPath: dest) as CFURL, kUTTypeJPEG, 1, nil)
                else { return }
            defer { CGImageDestinationFinalize(dest) }
            guard let imageSource = self.imageSource() else { return }
            guard let metadata = self.metadata()?.mutableCopy() as! NSMutableDictionary! else { return }
    
            let makerNote = NSMutableDictionary()
            makerNote.setObject(assetIdentifier, forKey: kFigAppleMakerNote_AssetIdentifier as NSCopying)
            metadata.setObject(makerNote, forKey: kCGImagePropertyMakerAppleDictionary as String as String as NSCopying)
            CGImageDestinationAddImageFromSource(dest, imageSource, 0, metadata)
        }
    
        fileprivate func metadata() -> NSDictionary? {
            return self.imageSource().flatMap {
                CGImageSourceCopyPropertiesAtIndex($0, 0, nil) as NSDictionary?
            }
        }
    
        fileprivate func imageSource() ->  CGImageSource? {
            return self.data().flatMap {
                CGImageSourceCreateWithData($0 as CFData, nil)
            }
        }
    
        fileprivate func data() -> Data? {
            return (try? Data(contentsOf: URL(fileURLWithPath: path)))
        }
    }
    

    发生了什么?如何使这项工作?

1 个答案:

答案 0 :(得分:0)

我终于通过使NSObject的{​​{1}} swift类子类不知道原因来完成这项工作,但它现在有效。

class JPEG:NSObject {
    ...
}