Hir*_*ren 86 share objective-c ios instagram swift
我的客户希望在Instagram,Twitter,Facebook上分享图像.
我已经完成了Twitter和Facebook,但没有在互联网上找到任何API或任何东西在Instagram上分享图像.可以在Instagram上分享图像吗?如果是的话怎么样?
当我查看Instagram的开发者网站时,我发现了Ruby on Rails和Python的Libraries.但是没有iOS Sdk的文档
我已根据instagram.com/developer从Instagram获取令牌,但现在不知道下一步与instagram图像共享该怎么做.
Hir*_*ren 69
最后我得到了答案.你不能直接在Instagram上发布图像.您必须使用UIDocumentInteractionController重新编写图像.
@property (nonatomic, retain) UIDocumentInteractionController *dic;
CGRect rect = CGRectMake(0 ,0 , 0, 0);
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIGraphicsEndImageContext();
NSString *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/test.igo"];
NSURL *igImageHookFile = [[NSURL alloc] initWithString:[[NSString alloc] initWithFormat:@"file://%@", jpgPath]];
self.dic.UTI = @"com.instagram.photo";
self.dic = [self setupControllerWithURL:igImageHookFile usingDelegate:self];
self.dic=[UIDocumentInteractionController interactionControllerWithURL:igImageHookFile];
[self.dic presentOpenInMenuFromRect: rect inView: self.view animated: YES ];
- (UIDocumentInteractionController *) setupControllerWithURL: (NSURL*) fileURL usingDelegate: (id <UIDocumentInteractionControllerDelegate>) interactionDelegate {
UIDocumentInteractionController *interactionController = [UIDocumentInteractionController interactionControllerWithURL: fileURL];
interactionController.delegate = interactionDelegate;
return interactionController;
}
Run Code Online (Sandbox Code Playgroud)
注意:一旦您重定向到Instagram应用程序,您将无法返回到您的应用程序.你必须再次打开你的应用程序
从这里下载源代码
Har*_*kar 27
这是一个完整的测试代码,上传图片+标题文字到Instagram ..
in.h文件
//Instagram
@property (nonatomic, retain) UIDocumentInteractionController *documentController;
-(void)instaGramWallPost
{
NSURL *instagramURL = [NSURL URLWithString:@"instagram://app"];
if([[UIApplication sharedApplication] canOpenURL:instagramURL]) //check for App is install or not
{
NSData *imageData = UIImagePNGRepresentation(imge); //convert image into .png format.
NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"insta.igo"]]; //add our image to the path
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the path (image)
NSLog(@"image saved");
CGRect rect = CGRectMake(0 ,0 , 0, 0);
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIGraphicsEndImageContext();
NSString *fileNameToSave = [NSString stringWithFormat:@"Documents/insta.igo"];
NSString *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:fileNameToSave];
NSLog(@"jpg path %@",jpgPath);
NSString *newJpgPath = [NSString stringWithFormat:@"file://%@",jpgPath];
NSLog(@"with File path %@",newJpgPath);
NSURL *igImageHookFile = [[NSURL alloc]initFileURLWithPath:newJpgPath];
NSLog(@"url Path %@",igImageHookFile);
self.documentController.UTI = @"com.instagram.exclusivegram";
self.documentController = [self setupControllerWithURL:igImageHookFile usingDelegate:self];
self.documentController=[UIDocumentInteractionController interactionControllerWithURL:igImageHookFile];
NSString *caption = @"#Your Text"; //settext as Default Caption
self.documentController.annotation=[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%@",caption],@"InstagramCaption", nil];
[self.documentController presentOpenInMenuFromRect:rect inView: self.view animated:YES];
}
else
{
NSLog (@"Instagram not found");
}
}
- (UIDocumentInteractionController *) setupControllerWithURL: (NSURL*) fileURL usingDelegate: (id <UIDocumentInteractionControllerDelegate>) interactionDelegate {
NSLog(@"file url %@",fileURL);
UIDocumentInteractionController *interactionController = [UIDocumentInteractionController interactionControllerWithURL: fileURL];
interactionController.delegate = interactionDelegate;
return interactionController;
}
Run Code Online (Sandbox Code Playgroud)
要么
-(void)instaGramWallPost
{
NSURL *myURL = [NSURL URLWithString:@"Your image url"];
NSData * imageData = [[NSData alloc] initWithContentsOfURL:myURL];
UIImage *imgShare = [[UIImage alloc] initWithData:imageData];
NSURL *instagramURL = [NSURL URLWithString:@"instagram://app"];
if([[UIApplication sharedApplication] canOpenURL:instagramURL]) //check for App is install or not
{
UIImage *imageToUse = imgShare;
NSString *documentDirectory=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *saveImagePath=[documentDirectory stringByAppendingPathComponent:@"Image.igo"];
NSData *imageData=UIImagePNGRepresentation(imageToUse);
[imageData writeToFile:saveImagePath atomically:YES];
NSURL *imageURL=[NSURL fileURLWithPath:saveImagePath];
self.documentController=[[UIDocumentInteractionController alloc]init];
self.documentController = [UIDocumentInteractionController interactionControllerWithURL:imageURL];
self.documentController.delegate = self;
self.documentController.annotation = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Testing"], @"InstagramCaption", nil];
self.documentController.UTI = @"com.instagram.exclusivegram";
UIViewController *vc = [UIApplication sharedApplication].keyWindow.rootViewController;
[self.documentController presentOpenInMenuFromRect:CGRectMake(1, 1, 1, 1) inView:vc.view animated:YES];
}
else {
DisplayAlertWithTitle(@"Instagram not found", @"")
}
}
Run Code Online (Sandbox Code Playgroud)
并将此内容写入.plist
<key>LSApplicationQueriesSchemes</key>
<array>
<string>instagram</string>
</array>
Run Code Online (Sandbox Code Playgroud)
gbk*_*gbk 19
您可以使用Instagram网址提供的方案之一
Instagram的官方文档在这里
与UIDocumentInteractionController共享
final class InstagramPublisher : NSObject {
private var documentsController:UIDocumentInteractionController = UIDocumentInteractionController()
func postImage(image: UIImage, view: UIView, result:((Bool)->Void)? = nil) {
guard let instagramURL = NSURL(string: "instagram://app") else {
if let result = result {
result(false)
}
return
}
if UIApplication.sharedApplication().canOpenURL(instagramURL) {
let jpgPath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent("instagrammFotoToShareName.igo")
if let image = UIImageJPEGRepresentation(image, 1.0) {
image.writeToFile(jpgPath, atomically: true)
let fileURL = NSURL.fileURLWithPath(jpgPath)
documentsController.URL = fileURL
documentsController.UTI = "com.instagram.exclusivegram"
documentsController.presentOpenInMenuFromRect(view.bounds, inView: view, animated: true)
if let result = result {
result(true)
}
} else if let result = result {
result(false)
}
} else {
if let result = result {
result(false)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)与直接重定向共享
import Photos
final class InstagramPublisher : NSObject {
func postImage(image: UIImage, result:((Bool)->Void)? = nil) {
guard let instagramURL = NSURL(string: "instagram://app") else {
if let result = result {
result(false)
}
return
}
let image = image.scaleImageWithAspectToWidth(640)
do {
try PHPhotoLibrary.sharedPhotoLibrary().performChangesAndWait {
let request = PHAssetChangeRequest.creationRequestForAssetFromImage(image)
let assetID = request.placeholderForCreatedAsset?.localIdentifier ?? ""
let shareURL = "instagram://library?LocalIdentifier=" + assetID
if UIApplication.sharedApplication().canOpenURL(instagramURL) {
if let urlForRedirect = NSURL(string: shareURL) {
UIApplication.sharedApplication().openURL(urlForRedirect)
}
}
}
} catch {
if let result = result {
result(false)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)将照片大小调整为建议大小的扩展名
import UIKit
extension UIImage {
// MARK: - UIImage+Resize
func scaleImageWithAspectToWidth(toWidth:CGFloat) -> UIImage {
let oldWidth:CGFloat = size.width
let scaleFactor:CGFloat = toWidth / oldWidth
let newHeight = self.size.height * scaleFactor
let newWidth = oldWidth * scaleFactor;
UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight))
drawInRect(CGRectMake(0, 0, newWidth, newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
Run Code Online (Sandbox Code Playgroud)不要忘记在plist中添加所需的方案
Run Code Online (Sandbox Code Playgroud)<key>LSApplicationQueriesSchemes</key> <array> <string>instagram</string> </array>
Pra*_*tel 17
希望这个答案能解决您的疑问.这将直接在Instagram中打开库文件夹而不是Camera.
NSURL *instagramURL = [NSURL URLWithString:@"instagram://app"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL])
{
NSURL *videoFilePath = [NSURL URLWithString:[NSString stringWithFormat:@"%@",[request downloadDestinationPath]]]; // Your local path to the video
NSString *caption = @"Some Preloaded Caption";
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeVideoAtPathToSavedPhotosAlbum:videoFilePath completionBlock:^(NSURL *assetURL, NSError *error) {
NSString *escapedString = [self urlencodedString:videoFilePath.absoluteString];
NSString *escapedCaption = [self urlencodedString:caption];
NSURL *instagramURL = [NSURL URLWithString:[NSString stringWithFormat:@"instagram://library?AssetPath=%@&InstagramCaption=%@",escapedString,escapedCaption]];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
[[UIApplication sharedApplication] openURL:instagramURL];
}
}];
Run Code Online (Sandbox Code Playgroud)
对于iOS 6及更高版本,您可以使用此UIActivity将图像上传到Instagram,它使用iOS挂钩具有相同的工作流程,但简化了开发:
https://github.com/coryalder/DMActivityInstagram
如果您不想使用UIDocumentInteractionController
import Photos
...
func postImageToInstagram(image: UIImage) {
UIImageWriteToSavedPhotosAlbum(image, self, #selector(SocialShare.image(_:didFinishSavingWithError:contextInfo:)), nil)
}
func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafePointer<Void>) {
if error != nil {
print(error)
}
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
let fetchResult = PHAsset.fetchAssetsWithMediaType(.Image, options: fetchOptions)
if let lastAsset = fetchResult.firstObject as? PHAsset {
let localIdentifier = lastAsset.localIdentifier
let u = "instagram://library?LocalIdentifier=" + localIdentifier
let url = NSURL(string: u)!
if UIApplication.sharedApplication().canOpenURL(url) {
UIApplication.sharedApplication().openURL(NSURL(string: u)!)
} else {
let alertController = UIAlertController(title: "Error", message: "Instagram is not installed", preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
这是我用细节实现的正确答案.在.h文件中
UIImageView *imageMain;
@property (nonatomic, strong) UIDocumentInteractionController *documentController;
Run Code Online (Sandbox Code Playgroud)
in.m文件只写
NSURL *instagramURL = [NSURL URLWithString:@"instagram://app"];
if([[UIApplication sharedApplication] canOpenURL:instagramURL])
{
CGFloat cropVal = (imageMain.image.size.height > imageMain.image.size.width ? imageMain.image.size.width : imageMain.image.size.height);
cropVal *= [imageMain.image scale];
CGRect cropRect = (CGRect){.size.height = cropVal, .size.width = cropVal};
CGImageRef imageRef = CGImageCreateWithImageInRect([imageMain.image CGImage], cropRect);
NSData *imageData = UIImageJPEGRepresentation([UIImage imageWithCGImage:imageRef], 1.0);
CGImageRelease(imageRef);
NSString *writePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"instagram.igo"];
if (![imageData writeToFile:writePath atomically:YES]) {
// failure
NSLog(@"image save failed to path %@", writePath);
return;
} else {
// success.
}
// send it to instagram.
NSURL *fileURL = [NSURL fileURLWithPath:writePath];
self.documentController = [UIDocumentInteractionController interactionControllerWithURL:fileURL];
self.documentController.delegate = self;
[self.documentController setUTI:@"com.instagram.exclusivegram"];
[self.documentController setAnnotation:@{@"InstagramCaption" : @"We are making fun"}];
[self.documentController presentOpenInMenuFromRect:CGRectMake(0, 0, 320, 480) inView:self.view animated:YES];
}
else
{
NSLog (@"Instagram not found");
}
Run Code Online (Sandbox Code Playgroud)
肯定会得到结果.例如,你会看到从底部的popover与instagram图像.点击它,玩得开心.
小智 5
我在我的应用程序中尝试了这个并且它工作正常(Swift)
import Foundation
import UIKit
class InstagramManager: NSObject, UIDocumentInteractionControllerDelegate {
private let kInstagramURL = "instagram://"
private let kUTI = "com.instagram.exclusivegram"
private let kfileNameExtension = "instagram.igo"
private let kAlertViewTitle = "Error"
private let kAlertViewMessage = "Please install the Instagram application"
var documentInteractionController = UIDocumentInteractionController()
// singleton manager
class var sharedManager: InstagramManager {
struct Singleton {
static let instance = InstagramManager()
}
return Singleton.instance
}
func postImageToInstagramWithCaption(imageInstagram: UIImage, instagramCaption: String, view: UIView) {
// called to post image with caption to the instagram application
let instagramURL = NSURL(string: kInstagramURL)
if UIApplication.sharedApplication().canOpenURL(instagramURL!) {
let jpgPath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(kfileNameExtension)
UIImageJPEGRepresentation(imageInstagram, 1.0)!.writeToFile(jpgPath, atomically: true)
let rect = CGRectMake(0,0,612,612)
let fileURL = NSURL.fileURLWithPath(jpgPath)
documentInteractionController.URL = fileURL
documentInteractionController.delegate = self
documentInteractionController.UTI = kUTI
// adding caption for the image
documentInteractionController.annotation = ["InstagramCaption": instagramCaption]
documentInteractionController.presentOpenInMenuFromRect(rect, inView: view, animated: true)
}
else {
// alert displayed when the instagram application is not available in the device
UIAlertView(title: kAlertViewTitle, message: kAlertViewMessage, delegate:nil, cancelButtonTitle:"Ok").show()
}
}
}
func sendToInstagram(){
let image = postImage
InstagramManager.sharedManager.postImageToInstagramWithCaption(image!, instagramCaption: "\(description)", view: self.view)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
90795 次 |
| 最近记录: |